package jsyf.oa.service.contract;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import jsyf.com.constant.SendConstant;
import jsyf.com.util.DateUtils;
import jsyf.com.util.FastJsonConvert;
import jsyf.oa.dao.attach.AttachModuleDao;
import jsyf.oa.dao.contract.*;
import jsyf.oa.dao.device.DeviceDisplaceDao;
import jsyf.oa.dao.system.*;
import jsyf.oa.dao.wechat.service_company.TokenDao;
import jsyf.oa.entity.attach.AttachModuleEntity;
import jsyf.oa.entity.attach.AttachmentEntity;
import jsyf.oa.entity.business.BusinessAuditEntity;
import jsyf.oa.entity.contract.*;
import jsyf.oa.entity.device.DeviceDisplaceEntity;
import jsyf.oa.entity.system.*;
import jsyf.oa.facade.contract.ReceivableFacade;
import jsyf.oa.ientity.IBaseEntity;
import jsyf.oa.service.wechat.service_company.HttpUtil;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.*;
import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.CONTRACT_APPLICATION_PASS;
import static jsyf.oa.dao.wechat.service_company.TokenDao.MsgTemplate.CONTRACT_APPLICATION_PASS_MESSAGE;
import static jsyf.oa.dao.wechat.service_company.TokenDao.PushTemplate.BUSINESS_AUDIT_NOTIFY;

@SuppressWarnings("all")
@Service
@Transactional(rollbackFor = Exception.class)
@com.alibaba.dubbo.config.annotation.Service(protocol = {"dubbo"})
public class ReceivableService implements ReceivableFacade {
    @Autowired
    private ContractMainDao contractMainDao;
    @Autowired
    private ContractSalesDao contractSalesDao;
    @Autowired
    private RepaymentDao repaymentDao;
    @Autowired
    private ReplacementDao replacementDao;
    @Autowired
    private DeviceDisplaceDao deviceDisplaceDao;
    @Autowired
    private UserDao userDao;
    @Autowired
    private TokenDao tokenDao;
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private MessageReceiverDao messageReceiverDao;
    @Autowired
    private FinancingDao financingDao;
    @Autowired
    private CheckDao checkDao;
    @Autowired
    private AttachModuleDao attachModuleDao;
    @Autowired
    private ContractHistoryDao contractHistoryDao;
    @Autowired
    private CollectionDao collectionDao;
    @Autowired
    private CompanyDao companyDao;
    @Autowired
    private AvailableDao availableDao;
    @Autowired
    private AuditDao auditDao;
    @Autowired
    private CopierDao copierDao;
    @Autowired
    private OverDueDetailDao overDueDetailDao;
    @Autowired
    private AuditHistoryDao auditHistoryDao;
    private static Boolean flag = true;
    //给客户发短信
    public static final String SENDER_CUS_REMIND = "%1s%2s您好，您购买的%3s%4s（%5s-%6s）月还款将于%7s到期，" +
            "请您按时还款。查看账单详情%8s" +
            "（如已还款，请忽略此短信。此短信内容仅供参考，不作为付款凭证。）";
    //给内部人员发短信
    public static final String SENDER_INNER_REMIND = "%1s%2s您好，您购买的%3s%4s（%5s-%6s）月还款将于%7s到期，" +
            "请您按时还款。 <a href='%8s'>点此查看账单</a>" +
            "（如已还款，请忽略此短信。此短信内容仅供参考，不作为付款凭证。）";

    //保存客户还款记录
    @Override
    public String saveAvailable(String jsonData) {
        AvailableEntity entity = JSON.toJavaObject(JSON.parseObject(jsonData), AvailableEntity.class);
        Integer rows = 0;
        if (entity.getAvailableMoney() != null &&
                entity.getAvailableMoney().compareTo(new BigDecimal("0.00")) > 0) {
            if ("0".equals(entity.getId()) || StringUtils.isBlank(entity.getId())) {
                rows = availableDao.add(entity);
            } else {
                rows = companyDao.update(entity);
            }
        }
        if (!entity.getCanUseMoney().equals(BigDecimal.ZERO)) {
            ContractMainEntity contractMainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(entity.getMainId());
            contractMainEntity.setAccountBalance(entity.getCanUseMoney());
            contractMainDao.update(contractMainEntity);
        }
        return rows == 0 ? "" : entity.getId();
    }

    //应收台账保存方法
    @Override
    public JSONObject receivableSave(String jsonData) {
        ContractEntity model = JSON.toJavaObject(JSON.parseObject(jsonData), ContractEntity.class);
        //获取所有表的信息
        ContractMainEntity contractMainEntity = model.getMain();//主表信息
        List<RepaymentEntity> repaymentaDKEntityList = model.getRepaymentDKList();//垫款条款
        List<RepaymentEntity> repaymentaFQEntityList = model.getRepaymentFQList();//内部分期
        List<RepaymentEntity> repaymentaRZEntityList = model.getRepaymentRZList();//融资分期
        List<FinancingEntity> financingRZEntityList = model.getFinancingRZList();//融资分期款跟踪
        List<FinancingEntity> financingRZDBEntityList = model.getFinancingRZDBList();//融资分期款跟踪
        List<RepaymentEntity> repaymentaRZDBEntityList = model.getRepaymentRZDBList();//融资分期
        List<RepaymentEntity> repaymentaSFEntityList = model.getRepaymentSFList();//首付款信息
        List<CollectionEntity> collectionList = model.getCollectionList();//催款记录
        List<AvailableEntity> availableEntityList = model.getAvailableList();//还款记录
        List<ContractHistoryEntity> regionManagerList = model.getRegionManagerList();//区域经理
        List<ContractHistoryEntity> bigRegionManagerList = model.getBigRegionManagerList();//大区经理
        List<ContractHistoryEntity> regionSupportList = model.getRegionSupportList();//区域支持
        List<ContractHistoryEntity> creditorManagerList = model.getCreditorManagerList();//债权经理
        List<ContractHistoryEntity> dataManagerList = model.getDataManagerList();//应收专员
        //18合格证
        //19发票
        //20所有权转移证书
        //查询附件
        List<JSONObject> certificate =model.getCertificate();
        List<JSONObject> invoice =model.getInvoice();
        List<JSONObject> ownershipTransfer =model.getOwnershipTransfer();
        //删除附件再添加,发票是只填加不删除
        if (certificate != null && certificate.size() > 0) {
            attachModuleDao.removeByCondition(" AND MODULE_ID = ? AND ATTACH_MODULE='18'", new String[]{contractMainEntity.getId()});
            for (JSONObject attach : certificate) {
                AttachmentEntity attachmentEntity = JSON.toJavaObject(attach, AttachmentEntity.class);
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attachmentEntity.getId());
                attachModuleEntity.setAttachModule(18);
                attachModuleEntity.setModuleId(contractMainEntity.getId());
                attachModuleDao.add(attachModuleEntity);
            }
        }
        if (invoice != null && invoice.size() > 0) {
            for (JSONObject attach : invoice) {
                AttachmentEntity attachmentEntity = JSON.toJavaObject(attach, AttachmentEntity.class);
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attachmentEntity.getId());
                attachModuleEntity.setAttachModule(19);
                attachModuleEntity.setModuleId(contractMainEntity.getId());
                attachModuleDao.add(attachModuleEntity);
            }
        }
        if (ownershipTransfer != null && ownershipTransfer.size() > 0) {
            attachModuleDao.removeByCondition(" AND MODULE_ID = ? AND ATTACH_MODULE='20'", new String[]{contractMainEntity.getId()});
            for (JSONObject attach : ownershipTransfer) {
                AttachmentEntity attachmentEntity = JSON.toJavaObject(attach, AttachmentEntity.class);
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attachmentEntity.getId());
                attachModuleEntity.setAttachModule(20);
                attachModuleEntity.setModuleId(contractMainEntity.getId());
                attachModuleDao.add(attachModuleEntity);
            }
        }
        //主表信息
        ContractMainEntity mainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(contractMainEntity.getId());
        contractMainEntity.setCreateTime(mainEntity.getCreateTime());
        contractMainEntity.setApplyTime(mainEntity.getApplyTime());
        if (contractMainEntity.getCustomerCredit().equals("已结清")) {
            contractMainEntity.setHaveSettle(1);
        }
        String mainId = contractMainEntity.getId();//主表的ID
        //删除历史人员记录
        contractHistoryDao.removeByCondition(" AND MAIN_ID=?", new String[]{mainId});
        //添加人员
        if (null != regionManagerList && regionManagerList.size() > 0) {
            for (int i = 0; i < regionManagerList.size(); i++) {
                JSONObject userEntity = userDao.getViewJSONById(regionManagerList.get(i).getHistoryManagerId());
                regionManagerList.get(i).setMainId(mainId);
                regionManagerList.get(i).setType(0);
                regionManagerList.get(i).setSortNo(i);
                if (userEntity != null) {
                    if (StringUtils.isNotEmpty(userEntity.getString("entryDate"))) {
                        regionManagerList.get(i).setEntryDate(userEntity.getString("entryDate"));
                    }
                    if (StringUtils.isNotEmpty(userEntity.getString("leaveDate"))) {
                        regionManagerList.get(i).setLeaveDate(userEntity.getString("leaveDate"));
                    }
                }
                contractHistoryDao.add(regionManagerList.get(i));
            }
            contractMainEntity.setTakeOverManagerId(
                    regionManagerList.get(regionManagerList.size() - 1).getHistoryManagerId()
            );
            contractMainEntity.setTakeOverManager(
                    regionManagerList.get(regionManagerList.size() - 1).getHistoryManagerName()
            );
        }
        if (null != bigRegionManagerList && bigRegionManagerList.size() > 0) {
            for (int i = 0; i < bigRegionManagerList.size(); i++) {
                JSONObject userEntity = userDao.getViewJSONById(bigRegionManagerList.get(i).getHistoryManagerId());
                bigRegionManagerList.get(i).setMainId(mainId);
                bigRegionManagerList.get(i).setType(1);
                bigRegionManagerList.get(i).setSortNo(i);
                if (userEntity != null) {
                    if (StringUtils.isNotEmpty(userEntity.getString("entryDate"))) {
                        bigRegionManagerList.get(i).setEntryDate(userEntity.getString("entryDate"));
                    }
                    if (StringUtils.isNotEmpty(userEntity.getString("leaveDate"))) {
                        bigRegionManagerList.get(i).setLeaveDate(userEntity.getString("leaveDate"));
                    }
                }
                contractHistoryDao.add(bigRegionManagerList.get(i));
            }
            contractMainEntity.setBigRegionManagerId(
                    bigRegionManagerList.get(bigRegionManagerList.size() - 1).getHistoryManagerId()
            );
            contractMainEntity.setBigRegionManagerName(
                    bigRegionManagerList.get(bigRegionManagerList.size() - 1).getHistoryManagerName()
            );
        }
        if (null != regionSupportList && regionSupportList.size() > 0) {
            for (int i = 0; i < regionSupportList.size(); i++) {
                JSONObject userEntity = userDao.getViewJSONById(regionSupportList.get(i).getHistoryManagerId());
                regionSupportList.get(i).setMainId(mainId);
                regionSupportList.get(i).setType(2);
                regionSupportList.get(i).setSortNo(i);
                if (userEntity != null) {
                    if (StringUtils.isNotEmpty(userEntity.getString("entryDate"))) {
                        regionSupportList.get(i).setEntryDate(userEntity.getString("entryDate"));
                    }
                    if (StringUtils.isNotEmpty(userEntity.getString("leaveDate"))) {
                        regionSupportList.get(i).setLeaveDate(userEntity.getString("leaveDate"));
                    }
                }
                contractHistoryDao.add(regionSupportList.get(i));
            }
            contractMainEntity.setRegionalSupportId(
                    regionSupportList.get(regionSupportList.size() - 1).getHistoryManagerId()
            );
            contractMainEntity.setRegionalSupportName(
                    regionSupportList.get(regionSupportList.size() - 1).getHistoryManagerName()
            );
        }
        if (null != creditorManagerList && creditorManagerList.size() > 0) {
            for (int i = 0; i < creditorManagerList.size(); i++) {
                JSONObject userEntity = userDao.getViewJSONById(creditorManagerList.get(i).getHistoryManagerId());
                creditorManagerList.get(i).setMainId(mainId);
                creditorManagerList.get(i).setType(3);
                creditorManagerList.get(i).setSortNo(i);
                if (userEntity != null) {
                    if (StringUtils.isNotEmpty(userEntity.getString("entryDate"))) {
                        creditorManagerList.get(i).setEntryDate(userEntity.getString("entryDate"));
                    }
                    if (StringUtils.isNotEmpty(userEntity.getString("leaveDate"))) {
                        creditorManagerList.get(i).setLeaveDate(userEntity.getString("leaveDate"));
                    }
                }
                contractHistoryDao.add(creditorManagerList.get(i));
            }
            contractMainEntity.setCreditManagerId(
                    creditorManagerList.get(creditorManagerList.size() - 1).getHistoryManagerId()
            );
            contractMainEntity.setCreditManagerName(
                    creditorManagerList.get(creditorManagerList.size() - 1).getHistoryManagerName()
            );
        }
        if (null != dataManagerList && dataManagerList.size() > 0) {
            for (int i = 0; i < dataManagerList.size(); i++) {
                JSONObject userEntity = userDao.getViewJSONById(dataManagerList.get(i).getHistoryManagerId());
                dataManagerList.get(i).setMainId(mainId);
                dataManagerList.get(i).setType(4);
                dataManagerList.get(i).setSortNo(i);
                if (userEntity != null) {
                    if (StringUtils.isNotEmpty(userEntity.getString("entryDate"))) {
                        dataManagerList.get(i).setEntryDate(userEntity.getString("entryDate"));
                    }
                    if (StringUtils.isNotEmpty(userEntity.getString("leaveDate"))) {
                        dataManagerList.get(i).setLeaveDate(userEntity.getString("leaveDate"));
                    }
                }
                contractHistoryDao.add(dataManagerList.get(i));
            }
            contractMainEntity.setDataOfficerId(
                    dataManagerList.get(dataManagerList.size() - 1).getHistoryManagerId()
            );
            contractMainEntity.setDataOfficerName(
                    dataManagerList.get(dataManagerList.size() - 1).getHistoryManagerName()
            );
        }
        //修改主表信息
        contractMainDao.update(contractMainEntity);
        //首付款信息
        if (null != repaymentaSFEntityList && repaymentaSFEntityList.size() > 0) {
            getRepaymentSave(repaymentaSFEntityList, mainId, model.getCreateUserId(), model.getCreateUserName());
        }

        //内部分期
        if (null != repaymentaFQEntityList && repaymentaFQEntityList.size() > 0) {
            getRepaymentSaveOvRe(repaymentaFQEntityList);
        }
        //融资分期
        if (null != repaymentaRZEntityList && repaymentaRZEntityList.size() > 0) {
            getRepaymentSaveOvRe(repaymentaRZEntityList);
        }
        //融资分期款跟踪

        if (null != financingRZEntityList && financingRZEntityList.size() > 0) {
            getRepaymentSaveOvReFn(financingRZEntityList);
        }
        //融资分期款跟踪

        if (null != financingRZDBEntityList && financingRZDBEntityList.size() > 0) {
            getRepaymentSaveOvReFn(financingRZDBEntityList);
        }
        //融资分期
        if (null != repaymentaRZDBEntityList && repaymentaRZDBEntityList.size() > 0) {
            getRepaymentSaveOvRe(repaymentaRZDBEntityList);
        }
        //首付款垫款信息
        if (contractMainEntity.getHaveRepayment() == 1) {
            if (null != repaymentaDKEntityList && repaymentaDKEntityList.size() > 0) {
                getRepaymentSave(repaymentaDKEntityList, mainId, model.getCreateUserId(), model.getCreateUserName());
            }
        }
        //还款记录
        if (null != availableEntityList && availableEntityList.size() > 0) {
            for (int i = 0; i < availableEntityList.size(); i++) {
                AvailableEntity entity = availableEntityList.get(i);
                if ("0".equals(entity.getId()) || StringUtils.isBlank(entity.getId())) {
                    if (StringUtils.isNotEmpty(entity.getAvailableDate())) {
                        entity.setMainId(mainId);
                        availableDao.add(entity);
                    }
                } else {
                    AvailableEntity availableEntity = (AvailableEntity) availableDao.getIBaseEntityById(entity.getId());
                    if (StringUtils.isNotEmpty(availableEntity.getAvailableDate())) {
                        availableEntity.setRepaymentAttachName(entity.getRepaymentAttachName());
                        availableEntity.setRepaymentAttachUrl(entity.getRepaymentAttachUrl());
                        availableDao.update(availableEntity);
                    }
                }
            }
        }
        //催收记录
        if (null != collectionList && collectionList.size() > 0) {
            for (int i = 0; i < collectionList.size(); i++) {
                CollectionEntity entity = collectionList.get(i);
                if ("0".equals(entity.getId()) || StringUtils.isBlank(entity.getId())) {
                    if (StringUtils.isNotEmpty(entity.getCollection())) {
                        entity.setMainId(mainId);
                        entity.setSortNo(i);
                        collectionDao.add(entity);
                    }
                } else {
                    CollectionEntity collectionEntity = (CollectionEntity) collectionDao.getIBaseEntityById(entity.getId());
                    if (StringUtils.isNotEmpty(entity.getCollection())) {
                        entity.setCreateTime(collectionEntity.getCreateTime());
                        collectionDao.update(entity);
                    }
                }
            }
        }
        JSONObject main = getAcountRepaymentById(contractMainEntity.getId());
        saveOver(main.toJSONString());
        JSONObject result = new JSONObject();
        result.put("flag", true);
        return result;
    }

    //详情页面
    @Override
    public JSONObject selectContractById(String jsonData) {
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String mainId = jsonPalams.getString("id");
        JSONObject jsonObject = getContractByCondition(mainId);
        return jsonObject;
    }

    //应收发消息
    @Override
    public Boolean receivableRemind() {
        //查询快到期的
        //快到期给区域经理发
        List<JSONObject> dq = contractMainDao.getJSONListKdq();
        Calendar c = Calendar.getInstance();
        String dateTime = DateUtils.parse(c.getTime(), "yyyy-MM-dd");
        for (int i = 0; i < dq.size(); i++) {
            JSONObject user = dq.get(i);
            //保存消息到消息表t_sys_message
            MessageEntity messageEntity = new MessageEntity();
            messageEntity.setCreateUserId(user.getString("takeOverManagerId"));
            messageEntity.setCreateTime(userDao.getCurrentTime());
            messageEntity.setContent("快到期");
            messageEntity.setMessageType(3);
            messageEntity.setDelFlag(0);
            messageEntity.setOpenUrl("/apply/accountReceivable/detailApp.html?id=" + user.getString("id") + "&pageType=look");
            messageEntity.setOpenTitle(String.format(YS_KDQ_MESSAGE,user.getString("buyer")));
            messageDao.add(messageEntity);
            //保存第一审核人信息到消息收件人表t_sys_message_receiver
            MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
            messageReceiverEntity.setMessageId(messageEntity.getId());
            messageReceiverEntity.setUserId(user.getString("takeOverManagerId"));
            messageReceiverEntity.setUserType(0);
            messageReceiverEntity.setReadFlag(0);
            messageReceiverDao.add(messageReceiverEntity);
            //发送企业微信
            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", messageEntity.getCreateUserId());
            msgObject.put("content", String.format(YS_KDQ_MESSAGE_WE,user.getString("buyer")
                    ,"http://oa.yingfeng365.com/page" + messageEntity.getOpenUrl()));
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
        }
        return true;
    }
    @Override
    public Boolean receivableRemindYq() {
        //查询逾期的
        List<JSONObject> yq=contractMainDao.getJSONListByCondition(" AND HAVE_OVERDUE='1' AND AUDIT_FLAG='1'",new Object[]{});
        for (int i = 0; i < yq.size(); i++) {
            JSONObject main = yq.get(i);
            String userIds="";
            //该条逾期信息中的区域经理，大区经理，区域总监，区域支持，销售管理，债权经理
            List userList=new ArrayList<>();
            //区域经理
            userList.add(main.getString("takeOverManagerId"));
            userIds=userIds+"'"+main.getString("takeOverManagerId")+"',";
            //大区经理
            userList.add(main.getString("bigRegionManagerId"));
            userIds=userIds+"'"+main.getString("bigRegionManagerId")+"',";
            //区域支持
            userList.add(main.getString("regionalSupportId"));
            userIds=userIds+"'"+main.getString("regionalSupportId")+"',";
            //债权经理
            userList.add(main.getString("creditManagerId"));
            userIds=userIds+"'"+main.getString("creditManagerId")+"',";
            if (StringUtils.isNotEmpty(userIds)){
                userIds=userIds.substring(0,userIds.length()-1);
            }
            //应收专员
            userList.add(main.getString("dataOfficerId"));
            userIds=userIds+"'"+main.getString("dataOfficerId")+"',";
            if (StringUtils.isNotEmpty(userIds)){
                userIds=userIds.substring(0,userIds.length()-1);
            }
            //区域总监,销售管理
            StringBuffer stringBuffer=new StringBuffer();
            stringBuffer.append(" AND roleName IN (\n" +
                    "\t\t'区域总监',\n" +
                    "\t\t'销售管理'\n" +
                    "\t)\n" +
                    "AND jobState !=1\n" +
                    "AND id NOT in("+userIds+")\n" +
                    "AND id IN (\n" +
                    "\tSELECT\n" +
                    "\t\tUSER_ID\n" +
                    "\tFROM\n" +
                    "\t\tt_sys_user_2_region\n" +
                    "\tWHERE\n" +
                    "\t\tREGION_ID IN (\n" +
                    "\t\t\tSELECT\n" +
                    "\t\t\t\tREGION_ID\n" +
                    "\t\t\tFROM\n" +
                    "\t\t\t\tt_sys_user_2_region\n" +
                    "\t\t\tWHERE\n" +
                    "\t\t\t\tUSER_ID = '"+main.getString("takeOverManagerId")+"'\n" +
                    "\t\t)\n" +
                    ")");
            List<JSONObject> json=userDao.getViewJSONListByCondition(stringBuffer.toString(),new Object[]{});
            if (json!=null&&json.size()>0){
                for (int j=0;j<json.size();j++){
                    userList.add(json.get(j).getString("id"));
                }
            }
            for (int j=0;j<userList.size();j++){
                //保存消息到消息表t_sys_message
            MessageEntity messageEntity = new MessageEntity();
            messageEntity.setCreateUserId(userList.get(j).toString());
            messageEntity.setCreateTime(userDao.getCurrentTime());
            messageEntity.setContent("逾期");
            messageEntity.setMessageType(3);
            messageEntity.setDelFlag(0);
            messageEntity.setOpenUrl("/apply/accountReceivable/detailApp.html?id="+main.getString("id")+"&pageType=look");
            messageEntity.setOpenTitle(String.format(YS_YQ_MESSAGE,main.getString("buyer")));
            messageDao.add(messageEntity);
            //保存第一审核人信息到消息收件人表t_sys_message_receiver
            MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
            messageReceiverEntity.setMessageId(messageEntity.getId());
            messageReceiverEntity.setUserId(userList.get(j).toString());
            messageReceiverEntity.setUserType(0);
            messageReceiverEntity.setReadFlag(0);
            messageReceiverDao.add(messageReceiverEntity);
            //发送企业微信
            JSONObject msgObject = new JSONObject();
            msgObject.put("userIds", messageEntity.getCreateUserId());
            msgObject.put("content", String.format(YS_YQ_MESSAGE_WE,main.getString("buyer"),
                    "http://oa.yingfeng365.com/page" + messageEntity.getOpenUrl()));
            tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
            }
        }
        return true;
    }
    //查询免息审核记录
    @Override
    public JSONObject getInterestFreeById(String jsonData) {
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String mainId = jsonPalams.getString("mainId");
        String repaymentId = jsonPalams.getString("repaymentId");
        ContractEntity entity = new ContractEntity();
        ContractMainEntity contractMainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(mainId);
        entity.setMain(contractMainEntity);
        List<RepaymentEntity> repaymentFQList = new ArrayList<>();
        List<RepaymentEntity> repaymentDKList = new ArrayList<>();
        List<RepaymentEntity> repaymentRZList = new ArrayList<>();
        List<RepaymentEntity> repaymentRZDBList = new ArrayList<>();
        List<RepaymentEntity> repaymentSFList = new ArrayList<>();
        repaymentSFList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition(" AND ID=? AND TYPE=3", new Object[]{repaymentId});
        repaymentDKList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition(" AND ID=? AND TYPE=1", new Object[]{repaymentId});
        repaymentFQList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition(" AND ID=? AND TYPE=0", new Object[]{repaymentId});
        repaymentRZList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition(" AND ID=? AND TYPE=2", new Object[]{repaymentId});
        repaymentRZDBList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition(" AND ID=? AND TYPE=4", new Object[]{repaymentId});
        if (null != repaymentSFList && repaymentSFList.size() > 0) {
            for (int i = 0; i < repaymentSFList.size(); i++) {
                RepaymentEntity repaymentSFEntity = repaymentSFList.get(i);
                List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition(" AND PARENT_ID=? AND TYPE=3 order by SORT_NO", new Object[]{repaymentSFEntity.getId()});
                repaymentSFEntity.setRepaymentParentList(repaymentParentList);
                calRemainingArrears(repaymentSFEntity, repaymentParentList, "1");

            }
        }
        if (null != repaymentDKList && repaymentDKList.size() > 0) {
            for (int i = 0; i < repaymentDKList.size(); i++) {
                RepaymentEntity repaymentDKEntity = repaymentDKList.get(i);
                List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition(" AND PARENT_ID=? AND TYPE=1 order by SORT_NO", new Object[]{repaymentDKEntity.getId()});
                repaymentDKEntity.setRepaymentParentList(repaymentParentList);
                calRemainingArrears(repaymentDKEntity, repaymentParentList, "1");

            }
        }
        if (null != repaymentFQList && repaymentFQList.size() > 0) {
            for (int i = 0; i < repaymentFQList.size(); i++) {
                RepaymentEntity repaymentFQEntity = repaymentFQList.get(i);
                List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition(" AND PARENT_ID=? AND TYPE=0 order by SORT_NO", new Object[]{repaymentFQEntity.getId()});
                repaymentFQEntity.setRepaymentParentList(repaymentParentList);
                calRemainingArrears(repaymentFQEntity, repaymentParentList, "1");

            }
        }
        if (null != repaymentRZList && repaymentRZList.size() > 0) {
            for (int i = 0; i < repaymentRZList.size(); i++) {
                RepaymentEntity repaymentRZEntity = repaymentRZList.get(i);
                List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition(" AND PARENT_ID=? AND TYPE=2 order by SORT_NO", new Object[]{repaymentRZEntity.getId()});
                repaymentRZEntity.setRepaymentParentList(repaymentParentList);
                if (contractMainEntity.getHaveDsdf() != 0) {
                    calRemainingArrears(repaymentRZEntity, repaymentParentList, "0");
                }
            }
        }
        if (null != repaymentRZDBList && repaymentRZDBList.size() > 0) {
            for (int i = 0; i < repaymentRZDBList.size(); i++) {
                RepaymentEntity repaymentRZDBEntity = repaymentRZDBList.get(i);
                List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition(" AND PARENT_ID=? AND TYPE=4 order by SORT_NO", new Object[]{repaymentRZDBEntity.getId()});
                repaymentRZDBEntity.setRepaymentParentList(repaymentParentList);
                if (contractMainEntity.getHaveDsdf() != 0) {
                    calRemainingArrears(repaymentRZDBEntity, repaymentParentList, "0");
                }
            }
        }
        entity.setRepaymentFQList(repaymentFQList);
        entity.setRepaymentRZList(repaymentRZList);
        entity.setRepaymentRZDBList(repaymentRZDBList);
        entity.setRepaymentSFList(repaymentSFList);
        entity.setRepaymentDKList(repaymentDKList);
        JSONObject jsonObject = (JSONObject) JSON.toJSON(entity);
        jsonObject.put("auditors", auditDao.getIBaseEntityByCondition(" AND MAIN_ID=?  AND MODULE_NAME='interestFree' AND RECEIVABLE_IDS LIKE '%" + repaymentId + "%'  order By auditSort", new Object[]{mainId}));
        jsonObject.put("copiers", copierDao.getIBaseEntityByCondition(" AND MAIN_ID=?  AND MODULE_NAME='interestFree' AND RECEIVABLE_IDS LIKE '%" + repaymentId + "%' ", new Object[]{mainId}));
        return jsonObject;
    }

    //查询免息list
    @Override
    public JSONObject getInterestFreeListById(String jsonData) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String mainId = jsonPalams.getString("id");
        String userId = jsonPalams.getString("userId");
        String interestFreeAuditFlag = jsonPalams.getString("interestFreeAuditFlag");
        String checkedIdString = "";
        ContractEntity entity = new ContractEntity();
        ContractMainEntity contractMainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(mainId);
        if (StringUtils.isBlank(contractMainEntity.getCustomerCredit())) {
            if (contractMainEntity.getHaveOverdue() == 1) {
                Integer overdueNo = contractMainEntity.getHaveOverdueNo();
                if (overdueNo <= 30) {
                    contractMainEntity.setCustomerCredit("1-1类：逾期1-30天");
                } else if (31 < overdueNo && overdueNo <= 60) {
                    contractMainEntity.setCustomerCredit("1-2类：逾期31-60天");
                } else {
                    contractMainEntity.setCustomerCredit("1-3类：逾期60天以上");
                }
            } else {
                contractMainEntity.setCustomerCredit("0类：无逾期");
            }
        }
        StringBuffer sb = new StringBuffer();
        sb.append(" AND OVERDUE_PENALTY != 0.00 \n");
        sb.append(" AND OVERDUE_PENALTY != '' \n");
        sb.append(" AND OVERDUE_PENALTY IS NOT NULL\n");
        if (interestFreeAuditFlag.equals("0")) {
            sb.append(" AND (INTEREST_FREE_FLAG =? OR INTEREST_FREE_FLAG =3)\n");
        } else if (interestFreeAuditFlag.equals("4")) {
            sb.append(" AND (INTEREST_FREE_FLAG =? OR INTEREST_FREE_FLAG in ('0','2','3'))\n");
        } else {
            sb.append(" AND INTEREST_FREE_FLAG =?\n");
        }
        sb.append(" AND MAIN_ID=? AND PARENT_ID=0 AND TYPE=? order by SORT_NO");
        List<RepaymentEntity> repaymentFQList = new ArrayList<>();
        List<RepaymentEntity> repaymentDKList = new ArrayList<>();
        List<RepaymentEntity> repaymentRZList = new ArrayList<>();
        List<RepaymentEntity> repaymentRZDBList = new ArrayList<>();
        List<RepaymentEntity> repaymentSFList = new ArrayList<>();
        List<FinancingEntity> financingRZList = new ArrayList<>();
        List<FinancingEntity> financingRZDBList = new ArrayList<>();
        repaymentSFList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition(sb.toString(), new Object[]{interestFreeAuditFlag, mainId, "3"});
        repaymentDKList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition(sb.toString(), new Object[]{interestFreeAuditFlag, mainId, "1"});
        repaymentFQList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition(sb.toString(), new Object[]{interestFreeAuditFlag, mainId, "0"});
        repaymentRZList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition(sb.toString(), new Object[]{interestFreeAuditFlag, mainId, "2"});
        repaymentRZDBList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition(sb.toString(), new Object[]{interestFreeAuditFlag, mainId, "4"});
        StringBuffer sbFn=new StringBuffer();
        sbFn.append(" AND JR_OVERDUE_PENALTY != 0.00 \n");
        sbFn.append(" AND JR_OVERDUE_PENALTY != '' \n");
        sbFn.append(" AND JR_OVERDUE_PENALTY IS NOT NULL\n");
        sbFn.append(" AND MAIN_ID=? AND PARENT_ID=0 AND TYPE=? order by SORT_NO");
        if (interestFreeAuditFlag.equals("0")){
            financingRZList = (List<FinancingEntity>) (Object) financingDao.getIBaseEntityByCondition(sbFn.toString(), new Object[]{mainId,"2"});
            financingRZDBList=(List<FinancingEntity>) (Object) financingDao.getIBaseEntityByCondition(sbFn.toString(), new Object[]{mainId,"4"});
        }
        if (null != repaymentSFList && repaymentSFList.size() > 0) {
            for (int i = 0; i < repaymentSFList.size(); i++) {
                checkedIdString = checkedIdString + repaymentSFList.get(i).getId() + ",";
                RepaymentEntity repaymentSFEntity = repaymentSFList.get(i);
                List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition(" AND PARENT_ID=? AND TYPE=3 order by SORT_NO", new Object[]{repaymentSFEntity.getId()});
                repaymentSFEntity.setRepaymentParentList(repaymentParentList);
                calRemainingArrears(repaymentSFEntity, repaymentParentList, "1");
            }
        }
        if (null != repaymentDKList && repaymentDKList.size() > 0) {
            for (int i = 0; i < repaymentDKList.size(); i++) {
                checkedIdString = checkedIdString + repaymentDKList.get(i).getId() + ",";
                RepaymentEntity repaymentDKEntity = repaymentDKList.get(i);
                List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition(" AND PARENT_ID=? AND TYPE=1 order by SORT_NO", new Object[]{repaymentDKEntity.getId()});
                repaymentDKEntity.setRepaymentParentList(repaymentParentList);
                calRemainingArrears(repaymentDKEntity, repaymentParentList, "1");
            }
        }
        if (null != repaymentFQList && repaymentFQList.size() > 0) {
            for (int i = 0; i < repaymentFQList.size(); i++) {
                checkedIdString = checkedIdString + repaymentFQList.get(i).getId() + ",";
                RepaymentEntity repaymentFQEntity = repaymentFQList.get(i);
                List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition(" AND PARENT_ID=? AND TYPE=0 order by SORT_NO", new Object[]{repaymentFQEntity.getId()});
                repaymentFQEntity.setRepaymentParentList(repaymentParentList);
                calRemainingArrears(repaymentFQEntity, repaymentParentList, "1");
            }
        }
        if (null != repaymentRZList && repaymentRZList.size() > 0) {
            for (int i = 0; i < repaymentRZList.size(); i++) {
                checkedIdString = checkedIdString + repaymentRZList.get(i).getId() + ",";
                RepaymentEntity repaymentRZEntity = repaymentRZList.get(i);
                List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition(" AND PARENT_ID=? AND TYPE=2 order by SORT_NO", new Object[]{repaymentRZEntity.getId()});
                repaymentRZEntity.setRepaymentParentList(repaymentParentList);
                if (contractMainEntity.getHaveDsdf() != 0) {
                    calRemainingArrears(repaymentRZEntity, repaymentParentList, "0");
                }
            }
        }
        if (null != repaymentRZDBList && repaymentRZDBList.size() > 0) {
            for (int i = 0; i < repaymentRZDBList.size(); i++) {
                checkedIdString = checkedIdString + repaymentRZDBList.get(i).getId() + ",";
                RepaymentEntity repaymentRZDBEntity = repaymentRZDBList.get(i);
                List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition(" AND PARENT_ID=? AND TYPE=4 order by SORT_NO", new Object[]{repaymentRZDBEntity.getId()});
                repaymentRZDBEntity.setRepaymentParentList(repaymentParentList);
                if (contractMainEntity.getHaveDsdf() != 0) {
                    calRemainingArrears(repaymentRZDBEntity, repaymentParentList, "0");
                }
            }

        }
        for (int i = 0; i < financingRZList.size(); i++) {
            FinancingEntity financingEntity = financingRZList.get(i);
            List<FinancingEntity> repaymentParentList = (List<FinancingEntity>) (Object) financingDao.getIBaseEntityByCondition(" AND PARENT_ID=? AND TYPE=2  order by SORT_NO", new Object[]{financingEntity.getId()});
            financingEntity.setRepaymentParentList(repaymentParentList);
            if (StringUtils.isNotEmpty(financingEntity.getFinancingDate())) {
                calRemainingArrears(financingEntity, repaymentParentList);
            }
        }
        for (int i = 0; i < financingRZDBList.size(); i++) {
            FinancingEntity financingEntity = financingRZDBList.get(i);
            List<FinancingEntity> repaymentParentList = (List<FinancingEntity>) (Object) financingDao.getIBaseEntityByCondition(" AND PARENT_ID=? AND TYPE=2  order by SORT_NO", new Object[]{financingEntity.getId()});
            financingEntity.setRepaymentParentList(repaymentParentList);
            if (StringUtils.isNotEmpty(financingEntity.getFinancingDate())) {
                calRemainingArrears(financingEntity, repaymentParentList);
            }
        }

        entity.setRepaymentFQList(repaymentFQList);
        entity.setRepaymentRZList(repaymentRZList);
        entity.setRepaymentRZDBList(repaymentRZDBList);
        entity.setRepaymentSFList(repaymentSFList);
        entity.setRepaymentDKList(repaymentDKList);
        entity.setFinancingRZDBList(financingRZDBList);
        entity.setFinancingRZList(financingRZList);

        //添加合同主表信息
        entity.setMain(contractMainEntity);
        ContractSalesEntity contractSalesEntity = (ContractSalesEntity) contractSalesDao.getIBaseEntityByCondition("AND MAIN_ID=? AND LOG_FLAG=0 ", new Object[]{mainId}).get(0);
        entity.setSales(contractSalesEntity);
        List<ReplacementEntity> replacementEntityList = (List<ReplacementEntity>) (Object) replacementDao.getIBaseEntityByCondition(" and main_id=?", new String[]{mainId});
        //查看是否是置换
        if (contractMainEntity.getHaveReplacement() == 1) {
            List<IBaseEntity> replacement = replacementDao.getIBaseEntityByCondition("AND MAIN_ID=? ", new Object[]{mainId});
            if (null != replacement && replacement.size() > 0) {
                ReplacementEntity replacementEntity = (ReplacementEntity) replacement.get(0);
                List<DeviceDisplaceEntity> zzj = new ArrayList<DeviceDisplaceEntity>();//旧挖掘机
                List<DeviceDisplaceEntity> wjj = new ArrayList<DeviceDisplaceEntity>();//旧装载机
                List<DeviceDisplaceEntity> fangWu = new ArrayList<DeviceDisplaceEntity>();//旧房屋置换
                List<DeviceDisplaceEntity> qiChe = new ArrayList<DeviceDisplaceEntity>();//旧汽车置换
                List<DeviceDisplaceEntity> other = new ArrayList<DeviceDisplaceEntity>();//其他置换信息
                String replacementsName = replacementEntity.getReplacementsName();
                DeviceDisplaceEntity deviceDisplaceEntity = new DeviceDisplaceEntity();
                if (!replacementsName.contains("zzj")) {
                    zzj.add(deviceDisplaceEntity);
                }
                if (!replacementsName.contains("wjj")) {
                    wjj.add(deviceDisplaceEntity);
                }
                if (!replacementsName.contains("fangWu")) {
                    fangWu.add(deviceDisplaceEntity);
                }
                if (!replacementsName.contains("qiChe")) {
                    qiChe.add(deviceDisplaceEntity);
                }
                if (!replacementsName.contains("other")) {
                    other.add(deviceDisplaceEntity);
                }
                List<DeviceDisplaceEntity> deviceDisplaces = (List<DeviceDisplaceEntity>) (Object) deviceDisplaceDao.getIBaseEntityByCondition("AND REPLACEMENT_ID=? AND DEL_FLAG=0", new Object[]{replacementEntity.getId()});
                for (DeviceDisplaceEntity deviceDisplace : deviceDisplaces) {
                    switch (deviceDisplace.getType()) {
                        //1-旧挖掘机，2-旧汽车，3-旧房屋，4-旧装载机，5-合同的其他情况
                        case 1:
                            wjj.add(deviceDisplace);
                            break;
                        case 2:
                            qiChe.add(deviceDisplace);
                            break;
                        case 3:
                            fangWu.add(deviceDisplace);
                            break;
                        case 4:
                            zzj.add(deviceDisplace);
                            break;
                        case 5:
                            other.add(deviceDisplace);
                            break;
                    }
                }
                //放入实体
                replacementEntity.setWjj(wjj);
                replacementEntity.setZzj(zzj);
                replacementEntity.setFangWu(fangWu);
                replacementEntity.setQiChe(qiChe);
                replacementEntity.setOther(other);
                entity.setReplacement(replacementEntity);
            }
        } else {
            ReplacementEntity replacementEntity = new ReplacementEntity();
            entity.setReplacement(replacementEntity);
        }
        if (!StringUtils.isBlank(checkedIdString)) {
            checkedIdString = checkedIdString.substring(0, checkedIdString.length() - 1);
        }
        JSONObject jsonObject = (JSONObject) JSON.toJSON(entity);
        if (!interestFreeAuditFlag.equals("0")) {
            jsonObject.put("auditors", auditDao.getIBaseEntityByCondition(" AND MAIN_ID=?  AND MODULE_NAME='interestFree' AND RECEIVABLE_IDS=?  order By auditSort", new Object[]{mainId, checkedIdString}));
            jsonObject.put("copiers", copierDao.getIBaseEntityByCondition(" AND MAIN_ID=?  AND MODULE_NAME='interestFree' AND RECEIVABLE_IDS=?", new Object[]{mainId, checkedIdString}));
        } else {
            JSONObject auditAndcoiper = getJSONByAuditAndCopier(userId, null, "");
            jsonObject.put("auditors", FastJsonConvert.convertJSONToArray(auditAndcoiper.getString("auditors"), JSONObject.class));
            jsonObject.put("copiers", FastJsonConvert.convertJSONToArray(auditAndcoiper.getString("copiers"), JSONObject.class));
        }
        jsonObject.put("auditHistory", auditHistoryDao.getIBaseEntityByCondition(" AND MAIN_ID=?  AND t_sys_audit_history.AUDIT_TYPE=9 AND RECEIVABLE_IDS=? AND AUDIT_FLAG=2 order By AUDITOR_NAME DESC", new Object[]{mainId, checkedIdString}));

        return jsonObject;
    }

    //保存免息list
    @Override
    public String saveInterestFreeList(String jsonData) {
        String checkedIdString = "no";
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String createUserId = jsonPalams.getString("createUserId");
        String createUserName = jsonPalams.getString("createUserName");
        String nowDate = DateUtils.nowDayByString(contractMainDao.getCurrentTime());
        ContractEntity model = JSON.toJavaObject(JSON.parseObject(jsonData), ContractEntity.class);
        //获取所有表的信息
        ContractMainEntity contractMainEntity = model.getMain();//主表
        List<RepaymentEntity> repaymentaDKEntityList = model.getRepaymentDKList();//垫款条款
        List<RepaymentEntity> repaymentaFQEntityList = model.getRepaymentFQList();//内部分期
        List<RepaymentEntity> repaymentaRZEntityList = model.getRepaymentRZList();//融资
        List<RepaymentEntity> repaymentaRZDBEntityList = model.getRepaymentRZDBList();//融资打包
        List<RepaymentEntity> repaymentaSFEntityList = model.getRepaymentSFList();//首付款信息
        String mainId = contractMainEntity.getId();//主表的ID
        //修改免除的主信息
        ContractMainEntity contractMainEntity1 = (ContractMainEntity) contractMainDao.getIBaseEntityById(contractMainEntity.getId());
        contractMainEntity1.setExempt(1);
        contractMainDao.update(contractMainEntity1);
        updateRepayMent(checkedIdString, repaymentaDKEntityList, 1);
        updateRepayMent(checkedIdString, repaymentaFQEntityList, 1);
        updateRepayMent(checkedIdString, repaymentaRZEntityList, 1);
        updateRepayMent(checkedIdString, repaymentaRZDBEntityList, 1);
        updateRepayMent(checkedIdString, repaymentaSFEntityList, 1);
        //修改其他信息
        saveMx(repaymentaDKEntityList, 1, createUserId, createUserName, nowDate);
        saveMx(repaymentaFQEntityList, 1, createUserId, createUserName, nowDate);
        saveMx(repaymentaRZEntityList, 1, createUserId, createUserName, nowDate);
        saveMx(repaymentaRZDBEntityList, 1, createUserId, createUserName, nowDate);
        saveMx(repaymentaSFEntityList, 1, createUserId, createUserName, nowDate);
        JSONObject main = getAcountRepaymentById(contractMainEntity.getId());
        saveAcountRepaymentListById(main.toJSONString());
        return "true";
    }

    //标记消息为已读 /0-审核人 /2-申请人 /1-抄送人
    private void messageReceiverRead(String mainId, Integer userType) {
        StringBuffer sb = new StringBuffer();
        List<String> arg = new ArrayList<>();
        if (!org.apache.commons.lang3.StringUtils.isBlank(mainId)) {
            sb.append("AND mainId=?");
            arg.add(mainId);
        }
        if (null != userType) {
            sb.append("AND receiverUserType=?");
            arg.add(userType.toString());
        }
        String receiverIds = "";
        List<JSONObject> jsonObjectList = messageDao.getViewJSONListByCondition(sb.toString(), arg.toArray());
        if (null != jsonObjectList && jsonObjectList.size() > 0) {
            for (int i = 0; i < jsonObjectList.size(); i++) {
                receiverIds += "'" + jsonObjectList.get(i).getString("receiverId") + "',";
            }
        }
        if (receiverIds.length() > 1) {
            receiverIds = receiverIds.substring(0, receiverIds.length() - 1);
        } else {
            receiverIds = null;
        }
        if (!org.apache.commons.lang3.StringUtils.isBlank(receiverIds)) {
            messageReceiverDao.updateReadFlag("T_SYS_MESSAGE_RECEIVER", "AND ID IN (" + receiverIds + ")");
        }
    }
    //免息审核
    @Override
    public Boolean applyAudit(String jsonData) {
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        String mainId = jsonPalams.getString("id");//获取主表Id
        String auditFlag = jsonPalams.getString("auditFlag");//审核状态
        String userId = jsonPalams.getString("userId");//当前审核人ID
        String advise = jsonPalams.getString("advise");//意见
        String checkedIdString = jsonPalams.getString("checkedIdString");//分期id
        String checkedIdStrings = jsonPalams.getString("checkedIdStrings");//分期id

        UserEntity userEntity = userDao.getById(userId);//获取当前审核人信息
        //获取合同列表
        ContractMainEntity contractMainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(mainId);//合同主表信息
        //获取免息列表
        List<RepaymentEntity> repaymentList = repaymentDao.getByConditionIBaseEntity(" and ID IN (" + checkedIdString + ")", new Object[]{});
        //修改主表审核信息----->>>-1未到轮次/初始状态>>>0当前等待审核>>>1通过>>>2驳回
        List<AuditEntity> auditEntityList = (List<AuditEntity>) (Object) auditDao.getIBaseEntityByCondition("and main_id=? and module_name=? AND RECEIVABLE_IDS=?  order by audit_sort", new Object[]{mainId, "interestFree", checkedIdStrings});
        AuditEntity auditEntityNow = null;
        for (int i = 0; i < auditEntityList.size(); i++) {
            AuditEntity audit = auditEntityList.get(i);
            if (audit.getAuditorId().equals(userId)) {
                //如果审核人==当前审核人
                auditEntityNow = auditEntityList.get(i);
                auditEntityNow.setAuditFlag(Integer.valueOf(auditFlag));
                auditEntityNow.setAuditTime(repaymentDao.getCurrentTime());
                auditEntityNow.setAuditAdvise(advise);
                auditDao.update(auditEntityNow);
                //企业号:发消息通知申请人  (不发送给抄送人)
                JSONObject msgObject = new JSONObject();
                msgObject.put("userIds", contractMainEntity.getApplyNameId());
                AuditHistoryEntity auditHistoryEntity = new AuditHistoryEntity();
                auditHistoryEntity.setAuditAdvise(advise);
                auditHistoryEntity.setAuditFlag(auditFlag);
                auditHistoryEntity.setAuditorId(userId);
                auditHistoryEntity.setAuditorName(userEntity.getName());
                auditHistoryEntity.setAuditTime(auditHistoryDao.getCurrentTime());
                auditHistoryEntity.setMainId(mainId);
                auditHistoryEntity.setAuditType(9);
                auditHistoryEntity.setReceivableIds(checkedIdStrings);
                auditHistoryDao.add(auditHistoryEntity);
                //如果是驳回，修改主表状态为驳回->2
                if (auditFlag.equals("2")) {
                    //修改合同表数据
                    contractMainEntity.setInterestFreeAuditFlag("2");
                    contractMainDao.update(contractMainEntity);
                    //修改分期表
                    updateRepayMent(checkedIdStrings, repaymentList, 3);
                    //企业号:给合同创建人发送消息
                    msgObject.put("content", String.format(FREE_OUT_REPAYMENT,
                            contractMainEntity.getApplyName(),
                            audit.getAuditAdvise(),
                            audit.getAuditorName(),
                            DateUtils.parse(contractMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
                    //推送: 给第一审核人推送红点提示
                    //tokenDao.sendJPushMsg(userId, String.format(CONTRACT_AUDIT_AUDIT, userEntity.getName()));
                    //标记以前的审核人、申请人消息为已读
                    messageReceiverRead(mainId, 0);
                    messageReceiverRead(mainId, 2);
                    //付款成功后给申请人发消息，保存消息到消息表t_sys_message
                    MessageEntity messageEntity = new MessageEntity();
                    messageEntity.setCreateUserId(contractMainEntity.getApplyNameId());
                    messageEntity.setCreateTime(contractMainDao.getCurrentTime());
                    messageEntity.setContent(String.format(FREE_OUT_REPAYMENT,
                            contractMainEntity.getApplyName(),
                            audit.getAuditAdvise(),
                            audit.getAuditorName(),
                            DateUtils.parse(contractMainDao.getCurrentTime(), "yyyy-MM-dd HH:mm")));
                    messageEntity.setMessageType(0);
                    messageEntity.setMainId(mainId);
                    messageEntity.setDelFlag(0);
                    messageEntity.setOpenUrl("apply/accountReceivable/detail.html?id=" + mainId + "&buyType=" + contractMainEntity.getBuyType());
                    messageEntity.setOpenTitle(String.format(FREE_APPLICATION_REJECT_MESSAGE, audit.getAuditorName()));
                    messageDao.add(messageEntity);

                    //保存消息到消息收件人表t_sys_message_receiver
                    MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                    messageReceiverEntity.setMessageId(messageEntity.getId());
                    messageReceiverEntity.setUserId(contractMainEntity.getApplyNameId());
                    messageReceiverEntity.setUserType(2);
                    messageReceiverEntity.setReadFlag(0);
                    messageReceiverDao.add(messageReceiverEntity);

                    //发消息
                    jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
                    break;
                }
                if ("1".equals(auditFlag)) {
                    if (i == auditEntityList.size() - 1) {
                        //如果是最后一个审核人
                        contractMainEntity.setInterestFreeAuditFlag(auditFlag);
                        contractMainEntity.setInterestFreeAuditId("");
                        contractMainEntity.setInterestFreeAuditName("");
                        contractMainDao.update(contractMainEntity);
                        //企业号: 最后一个审核通过,发送消息给申请人
                        msgObject.put("content", String.format(FREE_PASS_REPAYMENT,
                                contractMainEntity.getApplyName()));
                        tokenDao.sendTextMsg(JSON.toJSONString(msgObject));
                        //推送: 给第一审核人推送红点提示
                        //tokenDao.sendJPushMsg(userId, String.format(CONTRACT_AUDIT_NOTIFY, userEntity.getName()));
                        //标记以前的审核人、申请人消息为已读
                        messageReceiverRead(mainId, 0);
                        messageReceiverRead(mainId, 2);
                        //保存消息到消息表t_sys_message
                        MessageEntity messageEntity = new MessageEntity();
                        messageEntity.setCreateUserId(contractMainEntity.getApplyNameId());
                        messageEntity.setCreateTime(contractMainDao.getCurrentTime());
                        messageEntity.setContent(String.format(FREE_PASS_REPAYMENT,
                                contractMainEntity.getApplyName()));
                        messageEntity.setMessageType(0);
                        messageEntity.setMainId(mainId);
                        messageEntity.setDelFlag(0);
                        messageEntity.setOpenUrl("apply/accountReceivable/detail.html?id=" + mainId + "&buyType=" + contractMainEntity.getBuyType());
                        messageEntity.setOpenTitle(String.format(FREE_APPLICATION_PASS_MESSAGE, audit.getAuditorName()));
                        messageDao.add(messageEntity);

                        //保存消息到消息收件人表t_sys_message_receiver
                        MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                        messageReceiverEntity.setMessageId(messageEntity.getId());
                        messageReceiverEntity.setUserId(contractMainEntity.getApplyNameId());
                        messageReceiverEntity.setUserType(2);
                        messageReceiverEntity.setReadFlag(0);
                        messageReceiverDao.add(messageReceiverEntity);

                        //发消息
                        jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));

                        String createUserId = contractMainEntity.getApplyNameId();
                        String createUserName = contractMainEntity.getApplyName();
                        String nowDate = DateUtils.nowDayByString(contractMainDao.getCurrentTime());
                        //updateRepayMent(checkedIdStrings, repaymentList, 1);
                        saveMx(repaymentList, 1, createUserId, createUserName, nowDate);
                        JSONObject main = getAcountRepaymentById(contractMainEntity.getId());
                        saveAcountRepaymentListById(main.toJSONString());

                    } else {
                        AuditEntity auditEntityNext = auditEntityList.get(i + 1);
                        auditEntityNext.setAuditFlag(0);
                        auditDao.update(auditEntityNext);
                        contractMainEntity.setInterestFreeAuditId(auditEntityNext.getAuditorId());
                        contractMainEntity.setInterestFreeAuditName(auditEntityNext.getAuditorName());
                        contractMainDao.update(contractMainEntity);
                        //企业号: 审核通过,发送消息给申请人
                        msgObject.put("content", String.format(FREE_PASS_REPAYMENT,
                                contractMainEntity.getApplyName()));
                        tokenDao.sendTextMsg(JSON.toJSONString(msgObject));

                        //企业号: 给下一审核人发消息
                        JSONObject msgNextObject = new JSONObject();
                        String url = "http://oa.yingfeng365.com/page/apply/accountReceivable/shApp.html?id=" + mainId + "&pageType=look&shOrSq=sh&lookType=sh&userId=" + auditEntityNext.getAuditorId() + "&userName=" + auditEntityNext.getAuditorName();
                        ;
                        msgNextObject.put("userIds", auditEntityNext.getAuditorId());
                        msgNextObject.put("content", String.format(FREE_AUDIT_REPAYMENT,
                                auditEntityNext.getAuditorName(),
                                url,
                                contractMainEntity.getBuyer(),
                                contractMainEntity.getApplyName(),
                                DateUtils.parse(contractMainEntity.getApplyTime(), "yyyy-MM-dd HH:mm")));
                        tokenDao.sendTextMsg(JSON.toJSONString(msgNextObject));
                        //推送: 给第一审核人推送红点提示
                        //tokenDao.sendJPushMsg(userId, String.format(CONTRACT_AUDIT_NOTIFY, userEntity.getName()));
                        //标记以前的审核人、申请人消息为已读
                        messageReceiverRead(mainId, 0);
                        messageReceiverRead(mainId, 2);
                        //保存消息到消息表t_sys_message
                        MessageEntity messageEntity = new MessageEntity();
                        messageEntity.setCreateUserId(contractMainEntity.getApplyNameId());
                        messageEntity.setCreateTime(contractMainDao.getCurrentTime());
                        messageEntity.setContent( String.format(FREE_AUDIT_REPAYMENT_PC,
                                auditEntityNext.getAuditorName(),
                                contractMainEntity.getBuyer(),
                                contractMainEntity.getApplyName(),
                                DateUtils.parse(contractMainEntity.getApplyTime(), "yyyy-MM-dd HH:mm")));
                        messageEntity.setMessageType(0);
                        messageEntity.setMainId(mainId);
                        messageEntity.setDelFlag(0);
                        messageEntity.setOpenUrl("/page/apply/accountReceivable/InterestFreeSq.html?id=" + mainId + "&buyType=" + contractMainEntity.getBuyType()+ "&pageType=look&shOrSq=sh&lookType=sh");
                        messageEntity.setOpenTitle(String.format(FREE_AUDIT_AUDIT_MESSAGE, contractMainEntity.getApplyName()));
                        messageDao.add(messageEntity);

                        //保存消息到消息收件人表t_sys_message_receiver
                        MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                        messageReceiverEntity.setMessageId(messageEntity.getId());
                        messageReceiverEntity.setUserId(auditEntityNext.getAuditorId());
                        messageReceiverEntity.setUserType(0);
                        messageReceiverEntity.setReadFlag(0);
                        messageReceiverDao.add(messageReceiverEntity);

                        //发消息
                        jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
                        break;
                    }
                } else {
                    contractMainEntity.setInterestFreeAuditFlag(auditFlag);
                    contractMainEntity.setInterestFreeAuditName("");
                    contractMainEntity.setInterestFreeAuditId("");
                    contractMainDao.update(contractMainEntity);
                }
                break;
            }
        }
        return true;
    }

    //免息申请
    @Override
    public String interestFreeApply(String jsonData) {
        JSONObject json = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String checkedIdString = json.getString("checkedIdString");
        List<JSONObject> jsonObjectList = new ArrayList<>();
        ContractEntity model = JSON.toJavaObject(JSON.parseObject(jsonData), ContractEntity.class);
        //获取所有表的信息
        ContractMainEntity contractMainEntity = model.getMain();//主表
        List<RepaymentEntity> repaymentaDKEntityList = model.getRepaymentDKList();//垫款条款
        List<RepaymentEntity> repaymentaFQEntityList = model.getRepaymentFQList();//内部分期
        List<RepaymentEntity> repaymentaRZEntityList = model.getRepaymentRZList();//融资
        List<RepaymentEntity> repaymentaRZDBEntityList = model.getRepaymentRZDBList();//融资打包
        List<RepaymentEntity> repaymentaSFEntityList = model.getRepaymentSFList();//首付款信息
        String mainId = contractMainEntity.getId();//主表的ID

        //修改其他信息
        updateRepayMent(checkedIdString, repaymentaDKEntityList, 2);
        updateRepayMent(checkedIdString, repaymentaFQEntityList, 2);
        updateRepayMent(checkedIdString, repaymentaRZEntityList, 2);
        updateRepayMent(checkedIdString, repaymentaRZDBEntityList, 2);
        updateRepayMent(checkedIdString, repaymentaSFEntityList, 2);

        //修改主表信息
        ContractMainEntity contractMainEntity1 = (ContractMainEntity) contractMainDao.getIBaseEntityById(contractMainEntity.getId());
        contractMainEntity1.setApplyDepart(contractMainEntity.getApplyDepart());
        contractMainEntity1.setApplyName(contractMainEntity.getApplyName());
        contractMainEntity1.setApplyNameId(contractMainEntity.getApplyNameId());
        contractMainEntity1.setApplyTime(contractMainDao.getCurrentTime());
        contractMainEntity1.setExempt(0);
        contractMainDao.update(contractMainEntity1);
        //修改审核人抄送人，审核状态
        //删除现有的审核人和抄送人
        auditDao.removeByCondition("AND MAIN_ID = ? AND MODULE_NAME='interestFree' AND RECEIVABLE_IDS=?", new String[]{mainId, checkedIdString});
        copierDao.removeByCondition("AND MAIN_ID = ? AND MODULE_NAME='interestFree' AND RECEIVABLE_IDS=?", new String[]{mainId, checkedIdString});
        //获取审核人
        List<AuditEntity> auditors = model.getAuditors();
        //获取抄送人
        List<CopierEntity> copiers = model.getCopiers();
        //添加审核人
        if (null != auditors && auditors.size() > 0) {
            for (int i = 0; i < auditors.size(); i++) {
                AuditEntity auditEntity = new AuditEntity();
                auditEntity.setAuditorId(auditors.get(i).getAuditorId());
                auditEntity.setAuditorName(auditors.get(i).getAuditorName());
                auditEntity.setRoleName(auditors.get(i).getRoleName());
                auditEntity.setAuditSort(i);
                if (i == 0) {
                    String url = "http://oa.yingfeng365.com/page/apply/accountReceivable/shApp.html?id=" + mainId + "&pageType=look&shOrSq=sh&lookType=sh&userId=" + auditEntity.getAuditorId() + "&userName=" + auditEntity.getAuditorName();
                    //设置第一审核人状态
                    auditEntity.setAuditFlag(0);
                    ContractMainEntity contractMainEntity2 = (ContractMainEntity) contractMainDao.getIBaseEntityById(contractMainEntity.getId());
                    contractMainEntity2.setInterestFreeAuditName(auditEntity.getAuditorName());
                    contractMainEntity2.setInterestFreeAuditId(auditEntity.getAuditorId());
                    contractMainEntity2.setInterestFreeAuditFlag("0");
                    contractMainDao.update(contractMainEntity2);
                    //企业号: 给审核人发消息
                    JSONObject msgNextObject = new JSONObject();
                    msgNextObject.put("userIds", auditEntity.getAuditorId());
                    msgNextObject.put("content", String.format(FREE_AUDIT_REPAYMENT,
                            auditEntity.getAuditorName(),
                            url,
                            contractMainEntity1.getBuyer(),
                            contractMainEntity1.getApplyName(),
                            DateUtils.parse(contractMainEntity1.getApplyTime(), "yyyy-MM-dd HH:mm")));
                    tokenDao.sendTextMsg(JSON.toJSONString(msgNextObject));
                    //标记以前的审核人、申请人消息为已读
                    messageReceiverRead(mainId, 0);
                    messageReceiverRead(mainId, 2);

                    //保存消息到消息表t_sys_message
                    MessageEntity messageEntity = new MessageEntity();
                    messageEntity.setCreateUserId(contractMainEntity1.getApplyNameId());
                    messageEntity.setCreateTime(contractMainDao.getCurrentTime());
                    messageEntity.setContent(String.format(FREE_AUDIT_REPAYMENT_PC,
                            auditEntity.getAuditorName(),
                            contractMainEntity1.getBuyer(),
                            contractMainEntity1.getApplyName(),
                            DateUtils.parse(contractMainEntity1.getApplyTime(), "yyyy-MM-dd HH:mm")));
                    messageEntity.setMessageType(0);
                    messageEntity.setMainId(mainId);
                    messageEntity.setDelFlag(0);
                    messageEntity.setOpenUrl("/page/apply/accountReceivable/InterestFreeSq.html?id=" + mainId + "&buyType=" + contractMainEntity1.getBuyType()+ "&pageType=look&shOrSq=sh&lookType=sh");
                    messageEntity.setOpenTitle(String.format(FREE_AUDIT_AUDIT_MESSAGE, contractMainEntity1.getApplyName()));
                    messageDao.add(messageEntity);

                    //保存消息到消息收件人表t_sys_message_receiver
                    MessageReceiverEntity messageReceiverEntity = new MessageReceiverEntity();
                    messageReceiverEntity.setMessageId(messageEntity.getId());
                    messageReceiverEntity.setUserId(auditEntity.getAuditorId());
                    messageReceiverEntity.setUserType(0);
                    messageReceiverEntity.setReadFlag(0);
                    messageReceiverDao.add(messageReceiverEntity);

                    //发消息
                    jsonObjectList.add(getMessage(messageEntity, messageReceiverEntity));
                } else {
                    auditEntity.setAuditFlag(-1);
                }
                auditEntity.setModuleName("interestFree");//合同类型
                auditEntity.setMainId(mainId);
                auditEntity.setReceivableIds(checkedIdString);
                auditDao.add(auditEntity);
            }
        }
        //添加抄送人
        if (null != copiers && copiers.size() > 0) {
            for (int i = 0; i < copiers.size(); i++) {
                CopierEntity copierEntity = new CopierEntity();
                copierEntity.setCopierId(copiers.get(i).getCopierId());
                copierEntity.setCopierName(copiers.get(i).getCopierName());
                copierEntity.setModuleName("interestFree");//合同类型
                copierEntity.setReceivableIds(checkedIdString);

                copierEntity.setMainId(mainId);
                copierDao.add(copierEntity);
            }
        }
        return null;
    }

    //免息子表修改
    public void updateRepayMent(String checkedIdString, List<RepaymentEntity> repaymentEntity, Integer interestFreeFlag) {
        if (repaymentEntity != null && repaymentEntity.size() > 0) {
            for (int i = 0; i < repaymentEntity.size(); i++) {
                if (checkedIdString.indexOf(repaymentEntity.get(i).getId()) != -1 ||
                        (checkedIdString.equals("no") && repaymentEntity.get(i).getFreeMoney().compareTo(new BigDecimal(0.00)) > 0)) {
                    if (!StringUtils.isBlank(repaymentEntity.get(i).getId())) {
                        RepaymentEntity repaymentEntity1 = (RepaymentEntity) repaymentDao.getIBaseEntityById(repaymentEntity.get(i).getId());
                        if (checkedIdString.equals("no")) {
                            repaymentEntity1.setFreeMoney(repaymentEntity.get(i).getFreeMoney());
                        } else {
                            repaymentEntity1.setInterestFreeAttachName(repaymentEntity.get(i).getInterestFreeAttachName());
                            repaymentEntity1.setInterestFreeAttachUrl(repaymentEntity.get(i).getInterestFreeAttachUrl());
                        }
                        repaymentEntity1.setFreeMoney(repaymentEntity.get(i).getFreeMoney());
                        repaymentEntity1.setInterestFreeFlag(interestFreeFlag);
                        repaymentEntity1.setInterestFreeReason(repaymentEntity.get(i).getInterestFreeReason());
                        repaymentDao.update(repaymentEntity1);
                        if (repaymentEntity.get(i).getRepaymentParentList() != null && repaymentEntity.get(i).getRepaymentParentList().size() > 0) {
                            for (int j = 0; j < repaymentEntity.get(i).getRepaymentParentList().size(); j++) {
                                RepaymentEntity repaymentParent = (RepaymentEntity) repaymentDao.getIBaseEntityById(repaymentEntity.get(i).getRepaymentParentList().get(j).getId());
                                repaymentParent.setInterestFreeAttachName(repaymentEntity.get(i).getRepaymentParentList().get(j).getInterestFreeAttachName());
                                repaymentParent.setInterestFreeAttachUrl(repaymentEntity.get(i).getRepaymentParentList().get(j).getInterestFreeAttachUrl());
                                repaymentDao.update(repaymentParent);
                            }
                        }
                    }

                }


            }
        }
    }

    //免息保存方法
    public void saveMx(List<RepaymentEntity> repaymentEntity, Integer interestFreeFlag, String createUserId, String createUserName, String nowDate) {
        if (repaymentEntity != null && repaymentEntity.size() > 0) {
            for (int i = 0; i < repaymentEntity.size(); i++) {
                //插入最新的一条免息记录
                if (repaymentEntity.get(i).getFreeMoney().compareTo(new BigDecimal(0.00)) > 0) {
                    RepaymentEntity repaymentEntityMx = (RepaymentEntity) repaymentDao.getIBaseEntityById(repaymentEntity.get(i).getId());
                    //修改还款表主List
                    repaymentEntityMx.setInterestFreeFlag(interestFreeFlag);
                    repaymentEntityMx.setInterestFreeAttachName("");
                    repaymentEntityMx.setInterestFreeAttachUrl("");
                    repaymentDao.update(repaymentEntityMx);
                    //repaymentEntityMx.setInterestFreeReason("");
                    if (StringUtils.isBlank(repaymentEntityMx.getActualRepaymentDate()) && repaymentEntityMx.getRepaymentAmount().compareTo(new BigDecimal(0.00)) == 0) {
                        if (StringUtils.isNotEmpty(repaymentEntity.get(i).getInterestFreeReason())) {
                            repaymentEntityMx.setInterestFreeReason(repaymentEntity.get(i).getInterestFreeReason());
                        }
                        repaymentEntityMx.setActualRepaymentDate(nowDate);
                        repaymentEntityMx.setInterestFreeAttachName(repaymentEntity.get(i).getInterestFreeAttachName());
                        repaymentEntityMx.setInterestFreeAttachUrl(repaymentEntity.get(i).getInterestFreeAttachUrl());
                        //repaymentEntityMx.setInterestFreeReason(repaymentEntity.get(i).getInterestFreeReason());
                        repaymentEntityMx.setRepaymentAmount(repaymentEntity.get(i).getFreeMoney());
                        repaymentEntityMx.setHkType(3);
                        repaymentEntityMx.setCreateUserId(createUserId);
                        repaymentEntityMx.setType(repaymentEntityMx.getType());
                        repaymentEntityMx.setCreateUserName(createUserName);
                        repaymentEntityMx.setCreateDate(DateUtils.nowSFByString(repaymentDao.getCurrentTime()));
                        repaymentEntityMx.setCreateTime(repaymentDao.getCurrentTime());
                        repaymentDao.update(repaymentEntityMx);
                    } else {
                        //查询跟踪款
                        List<RepaymentEntity> repaymentParentListMx = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND PARENT_ID=?  order by SORT_NO", new Object[]{repaymentEntity.get(i).getId()});
                        //查询最后一条子list
                        RepaymentEntity repaymentEntityParentMx = new RepaymentEntity();
                        if (repaymentParentListMx != null && repaymentParentListMx.size() > 0) {
                            repaymentEntityParentMx.setSortNo(repaymentParentListMx.size());
                        } else {
                            repaymentEntityParentMx.setSortNo(0);
                        }
                        repaymentEntityParentMx.setMainId(repaymentEntity.get(i).getMainId());
                        repaymentEntityParentMx.setHkType(3);
                        repaymentEntityParentMx.setType(repaymentEntityMx.getType());
                        repaymentEntityParentMx.setInterestFreeAttachName(repaymentEntity.get(i).getInterestFreeAttachName());
                        repaymentEntityParentMx.setInterestFreeAttachUrl(repaymentEntity.get(i).getInterestFreeAttachUrl());
                        //repaymentEntityParentMx.setInterestFreeReason(repaymentEntity.get(i).getInterestFreeReason());
                        repaymentEntityParentMx.setParentId(repaymentEntity.get(i).getId());
                        repaymentEntityParentMx.setRepaymentDate(repaymentEntity.get(i).getRepaymentDate());
                        repaymentEntityParentMx.setRemainingArrears(new BigDecimal(0.00));
                        repaymentEntityParentMx.setOverduePenalty(new BigDecimal(0.00));
                        repaymentEntityParentMx.setTotal(repaymentEntity.get(i).getTotal());
                        repaymentEntityParentMx.setPrincipal(repaymentEntity.get(i).getPrincipal());
                        repaymentEntityParentMx.setInterest(repaymentEntity.get(i).getInterest());
                        repaymentEntityParentMx.setContractRepaymentAmount(repaymentEntity.get(i).getContractRepaymentAmount());
                        repaymentEntityParentMx.setCreateUserId(createUserId);
                        repaymentEntityParentMx.setCreateUserName(createUserName);
                        repaymentEntityParentMx.setActualRepaymentDate(nowDate);
                        repaymentEntityParentMx.setRepaymentAmount(repaymentEntity.get(i).getFreeMoney());
                        repaymentEntityParentMx.setRemark(repaymentEntity.get(i).getInterestFreeReason());
                        repaymentEntityParentMx.setCreateDate(DateUtils.nowSFByString(repaymentDao.getCurrentTime()));
                        repaymentEntityParentMx.setCreateTime(repaymentDao.getCurrentTime());
                        repaymentDao.add(repaymentEntityParentMx);
                    }
                }
            }
        }

    }

    //获取抄送人和收件人
    public JSONObject getJSONByAuditAndCopier(String userId, String mainId, String auditFlag) {
        JSONObject results = new JSONObject();
        //获取审核人
        List<JSONObject> auditors = new ArrayList<>();
        //查询抄送人
        List<JSONObject> copiers = new ArrayList<>();
        JSONObject auditentity = new JSONObject();
        auditentity.put("auditorId", "20180307111342A6AFC442DC05FD86E2");
        auditentity.put("auditorName", "隋华");
        auditentity.put("roleName", "债权总监");
        auditentity.put("auditFlag", "-1");
        auditors.add(auditentity);
        JSONObject auditentity2 = new JSONObject();
        auditentity2.put("auditorId", "20181029131941189298E733B95017AF");
        auditentity2.put("auditorName", "贺建荣");
        auditentity2.put("roleName", "集团副总裁");
        auditentity2.put("auditFlag", "-1");
        auditors.add(auditentity2);
        JSONObject auditentity3 = new JSONObject();
        auditentity3.put("auditorId", "2017121618514C22B68296F31AF8DDE2");
        auditentity3.put("auditorName", "谈小中");
        auditentity3.put("roleName", "总裁");
        auditentity3.put("auditFlag", "-1");
        auditors.add(auditentity3);
        JSONObject copier = new JSONObject();
        copier.put("copierId", "201711271733404C9DA1461F2421F828");
        copier.put("copierName", "曹国玉");
        copier.put("roleName", "后台管理");
        copier.put("auditFlag", "-1");
        copiers.add(copier);
        results.put("auditors", auditors);
        results.put("copiers", copiers);
        return results;
    }

    //查询冲抵list
    @Override
    public JSONObject getAcountRepaymentListById(String jsonData) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String mainId = jsonPalams.getString("id");
        List<JSONObject> repaymentFQList = new ArrayList<>();
        List<JSONObject> repaymentDKList = new ArrayList<>();
        List<JSONObject> repaymentRZList = new ArrayList<>();
        List<JSONObject> repaymentRZDBList = new ArrayList<>();
        List<JSONObject> repaymentSFList = new ArrayList<>();
        List<JSONObject> financingRZList = new JSONArray();
        List<JSONObject> financingRZDBList = new JSONArray();
        ContractMainEntity contractMainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(mainId);
        repaymentSFList = repaymentDao.getAcountRepaymentList(mainId, "3");
        repaymentDKList = repaymentDao.getAcountRepaymentList(mainId, "1");
        repaymentFQList = repaymentDao.getAcountRepaymentList(mainId, "0");
        repaymentRZList = repaymentDao.getAcountRepaymentList(mainId, "2");
        repaymentRZDBList = repaymentDao.getAcountRepaymentList(mainId, "4");
        financingRZList = financingDao.getJSONListByCondition(" AND PARENT_ID='0' AND MAIN_ID=? AND TYPE=2 " +
                " AND (REMAINING_ARREARS !='0.00' OR JR_OVERDUE_PENALTY != '0.00' OR\n" +
                "FINANCING_DATE =(SELECT FINANCING_DATE FROM t_con_financingment WHERE (FINANCING_DATE >= CURDATE())\n" +
                "AND TYPE = 2 AND MAIN_ID = ? ORDER BY FINANCING_DATE LIMIT 1)) " +
                " OR\n" +
                "ID in(SELECT PARENT_ID FROM t_con_financingment \n" +
                "WHERE ADVANCES_DATE=CURDATE() \n" +
                "AND MAIN_ID = ? AND TYPE=2)\n" +
                "OR \n" +
                "ID in(SELECT ID FROM t_con_financingment \n" +
                "WHERE ADVANCES_DATE=CURDATE() \n" +
                "AND MAIN_ID = ?\n" +
                "AND MAIN_ID = ? AND TYPE=2\n" +
                "AND PARENT_ID = '0') ORDER BY SORT_NO", new Object[]{mainId, mainId, mainId, mainId, mainId});
        financingRZDBList = financingDao.getJSONListByCondition(" AND PARENT_ID='0' AND MAIN_ID=? AND TYPE=4 " +
                " AND (REMAINING_ARREARS !='0.00' OR JR_OVERDUE_PENALTY != '0.00' OR\n" +
                "FINANCING_DATE =(SELECT FINANCING_DATE FROM t_con_financingment WHERE (FINANCING_DATE >= CURDATE())\n" +
                "AND TYPE = 4 AND MAIN_ID = ? ORDER BY FINANCING_DATE LIMIT 1)) " +
                " OR\n" +
                "ID in(SELECT PARENT_ID FROM t_con_financingment \n" +
                "WHERE ADVANCES_DATE=CURDATE() \n" +
                "AND MAIN_ID = ? AND TYPE =4 \n" +
                "AND MAIN_ID = ?)\n" +
                "OR \n" +
                "ID in(SELECT ID FROM t_con_financingment \n" +
                "WHERE ADVANCES_DATE=CURDATE() \n" +
                "AND MAIN_ID = ? AND TYPE =4 \n" +
                "AND PARENT_ID = '0') ORDER BY SORT_NO", new Object[]{mainId, mainId, mainId, mainId, mainId});
        if (null != repaymentSFList && repaymentSFList.size() > 0) {
            for (int i = 0; i < repaymentSFList.size(); i++) {
                JSONObject repaymentSFEntity = repaymentSFList.get(i);
                List<JSONObject> repaymentParentList = (List<JSONObject>) (Object) repaymentDao.getJSONListByCondition(" AND PARENT_ID=? AND TYPE=3 order by SORT_NO", new Object[]{repaymentSFEntity.getString("id")});
                repaymentSFEntity.put("repaymentParentList", repaymentParentList);
                calRemainingArrears(repaymentSFEntity, repaymentParentList, "1");
            }
        }
        if (null != repaymentDKList && repaymentDKList.size() > 0) {
            for (int i = 0; i < repaymentDKList.size(); i++) {
                JSONObject repaymentDKEntity = repaymentDKList.get(i);
                List<JSONObject> repaymentParentList = (List<JSONObject>) (Object) repaymentDao.getJSONListByCondition(" AND PARENT_ID=? AND TYPE=1 order by SORT_NO", new Object[]{repaymentDKEntity.getString("id")});
                repaymentDKEntity.put("repaymentParentList", repaymentParentList);
                calRemainingArrears(repaymentDKEntity, repaymentParentList, "1");
            }
        }
        if (null != repaymentFQList && repaymentFQList.size() > 0) {
            for (int i = 0; i < repaymentFQList.size(); i++) {
                JSONObject repaymentFQEntity = repaymentFQList.get(i);
                List<JSONObject> repaymentParentList = (List<JSONObject>) (Object) repaymentDao.getJSONListByCondition(" AND PARENT_ID=? AND TYPE=0 order by SORT_NO", new Object[]{repaymentFQEntity.getString("id")});
                repaymentFQEntity.put("repaymentParentList", repaymentParentList);
                calRemainingArrears(repaymentFQEntity, repaymentParentList, "1");
            }
        }
        if (null != repaymentRZList && repaymentRZList.size() > 0) {
            for (int i = 0; i < repaymentRZList.size(); i++) {
                JSONObject repaymentRZEntity = repaymentRZList.get(i);
                List<JSONObject> repaymentParentList = (List<JSONObject>) (Object) repaymentDao.getJSONListByCondition(" AND PARENT_ID=? AND TYPE=2 order by SORT_NO", new Object[]{repaymentRZEntity.getString("id")});
                repaymentRZEntity.put("repaymentParentList", repaymentParentList);
                if (contractMainEntity.getHaveDsdf() != 0) {
                    calRemainingArrears(repaymentRZEntity, repaymentParentList, "0");
                } else {
                    repaymentRZEntity.put("everyRemainingArrear", new BigDecimal(0.00));
                    repaymentRZEntity.put("everyOverduePenalty", new BigDecimal(0.00));
                    if (null != repaymentParentList && repaymentParentList.size() > 0) {
                        for (int j = 0; j < repaymentParentList.size(); j++) {
                            repaymentParentList.get(j).put("everyRemainingArrear", new BigDecimal(0.00));
                            repaymentParentList.get(j).put("everyOverduePenalty", new BigDecimal(0.00));
                        }

                    }
                }
            }
        }
        if (null != repaymentRZDBList && repaymentRZDBList.size() > 0) {
            for (int i = 0; i < repaymentRZDBList.size(); i++) {
                JSONObject repaymentRZDBEntity = repaymentRZDBList.get(i);
                List<JSONObject> repaymentParentList = (List<JSONObject>) (Object) repaymentDao.getJSONListByCondition(" AND PARENT_ID=? AND TYPE=4 order by SORT_NO", new Object[]{repaymentRZDBEntity.getString("id")});
                repaymentRZDBEntity.put("repaymentParentList", repaymentParentList);
                if (contractMainEntity.getHaveDsdf() != 0) {
                    calRemainingArrears(repaymentRZDBEntity, repaymentParentList, "0");
                } else {
                    repaymentRZDBEntity.put("everyRemainingArrear", new BigDecimal(0.00));
                    repaymentRZDBEntity.put("everyOverduePenalty", new BigDecimal(0.00));
                    if (null != repaymentParentList && repaymentParentList.size() > 0) {
                        for (int j = 0; j < repaymentParentList.size(); j++) {
                            repaymentParentList.get(j).put("everyRemainingArrear", new BigDecimal(0.00));
                            repaymentParentList.get(j).put("everyOverduePenalty", new BigDecimal(0.00));
                        }

                    }
                }
            }

        }

        if (null != financingRZList && financingRZList.size() > 0) {
            for (int i = 0; i < financingRZList.size(); i++) {
                JSONObject financingEntity = financingRZList.get(i);
                List<JSONObject> repaymentParentList = (List<JSONObject>) (Object) financingDao.getJSONListByCondition(" AND PARENT_ID=? AND TYPE=2  order by SORT_NO", new Object[]{financingEntity.getString("id")});
                financingEntity.put("repaymentParentList", repaymentParentList);
                calRemainingArrears(financingEntity, repaymentParentList);
            }
        }
        if (null != financingRZDBList && financingRZDBList.size() > 0) {
            for (int i = 0; i < financingRZDBList.size(); i++) {
                JSONObject financingEntity = financingRZDBList.get(i);
                List<JSONObject> repaymentParentList = (List<JSONObject>) (Object) financingDao.getJSONListByCondition(" AND PARENT_ID=? AND TYPE=4  order by SORT_NO", new Object[]{financingEntity.getString("id")});
                financingEntity.put("repaymentParentList", repaymentParentList);
                calRemainingArrears(financingEntity, repaymentParentList);
            }
        }
        JSONObject result = new JSONObject();
        result.put("main", contractMainEntity);
        result.put("repaymentFQList", repaymentFQList);
        result.put("repaymentDKList", repaymentDKList);
        result.put("repaymentRZList", repaymentRZList);
        result.put("repaymentRZDBList", repaymentRZDBList);
        result.put("repaymentSFList", repaymentSFList);
        result.put("financingRZList", financingRZList);
        result.put("financingRZDBList", financingRZDBList);
        return result;

    }

    public JSONObject getAcountRepaymentById(String mainId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<JSONObject> repaymentFQList = new ArrayList<>();
        List<JSONObject> repaymentDKList = new ArrayList<>();
        List<JSONObject> repaymentRZList = new ArrayList<>();
        List<JSONObject> repaymentRZDBList = new ArrayList<>();
        List<JSONObject> repaymentSFList = new ArrayList<>();
        List<JSONObject> financingRZList = new JSONArray();
        List<JSONObject> financingRZDBList = new JSONArray();
        ContractMainEntity contractMainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(mainId);
        repaymentSFList = repaymentDao.getAcountRepaymentList(mainId, "3");
        repaymentDKList = repaymentDao.getAcountRepaymentList(mainId, "1");
        repaymentFQList = repaymentDao.getAcountRepaymentList(mainId, "0");
        repaymentRZList = repaymentDao.getAcountRepaymentList(mainId, "2");
        repaymentRZDBList = repaymentDao.getAcountRepaymentList(mainId, "4");
        financingRZList = financingDao.getJSONListByCondition(" AND PARENT_ID='0' AND MAIN_ID=? AND TYPE=2 " +
                " AND (REMAINING_ARREARS !='0.00' OR JR_OVERDUE_PENALTY != '0.00' OR\n" +
                "FINANCING_DATE =(SELECT FINANCING_DATE FROM t_con_financingment WHERE (FINANCING_DATE > CURDATE())\n" +
                "AND TYPE = 2 AND MAIN_ID = ? ORDER BY FINANCING_DATE LIMIT 1)) " +
                " OR\n" +
                "ID in(SELECT PARENT_ID FROM t_con_financingment \n" +
                "WHERE ADVANCES_DATE=CURDATE() \n" +
                "AND MAIN_ID = ? AND TYPE=2)\n" +
                "OR \n" +
                "ID in(SELECT ID FROM t_con_financingment \n" +
                "WHERE ADVANCES_DATE=CURDATE() \n" +
                "AND MAIN_ID = ?\n" +
                "AND MAIN_ID = ? AND TYPE=2\n" +
                "AND PARENT_ID = '0') ORDER BY SORT_NO", new Object[]{mainId, mainId, mainId, mainId, mainId});
        financingRZDBList = financingDao.getJSONListByCondition(" AND PARENT_ID='0' AND MAIN_ID=? AND TYPE=4 " +
                " AND (REMAINING_ARREARS !='0.00' OR JR_OVERDUE_PENALTY != '0.00' OR\n" +
                "FINANCING_DATE =(SELECT FINANCING_DATE FROM t_con_financingment WHERE (FINANCING_DATE > CURDATE())\n" +
                "AND TYPE = 4 AND MAIN_ID = ? ORDER BY FINANCING_DATE LIMIT 1)) " +
                " OR\n" +
                "ID in(SELECT PARENT_ID FROM t_con_financingment \n" +
                "WHERE ADVANCES_DATE=CURDATE() \n" +
                "AND MAIN_ID = ? AND TYPE =4 \n" +
                "AND MAIN_ID = ?)\n" +
                "OR \n" +
                "ID in(SELECT ID FROM t_con_financingment \n" +
                "WHERE ADVANCES_DATE=CURDATE() \n" +
                "AND MAIN_ID = ? AND TYPE =4 \n" +
                "AND PARENT_ID = '0') ORDER BY SORT_NO", new Object[]{mainId, mainId, mainId, mainId, mainId});
        if (null != repaymentSFList && repaymentSFList.size() > 0) {
            for (int i = 0; i < repaymentSFList.size(); i++) {
                JSONObject repaymentSFEntity = repaymentSFList.get(i);
                List<JSONObject> repaymentParentList = (List<JSONObject>) (Object) repaymentDao.getJSONListByCondition(" AND PARENT_ID=? AND TYPE=3 order by SORT_NO", new Object[]{repaymentSFEntity.getString("id")});
                repaymentSFEntity.put("repaymentParentList", repaymentParentList);
                calRemainingArrears(repaymentSFEntity, repaymentParentList, "1");
            }
        }
        if (null != repaymentDKList && repaymentDKList.size() > 0) {
            for (int i = 0; i < repaymentDKList.size(); i++) {
                JSONObject repaymentDKEntity = repaymentDKList.get(i);
                List<JSONObject> repaymentParentList = (List<JSONObject>) (Object) repaymentDao.getJSONListByCondition(" AND PARENT_ID=? AND TYPE=1 order by SORT_NO", new Object[]{repaymentDKEntity.getString("id")});
                repaymentDKEntity.put("repaymentParentList", repaymentParentList);
                calRemainingArrears(repaymentDKEntity, repaymentParentList, "1");
            }
        }
        if (null != repaymentFQList && repaymentFQList.size() > 0) {
            for (int i = 0; i < repaymentFQList.size(); i++) {
                JSONObject repaymentFQEntity = repaymentFQList.get(i);
                List<JSONObject> repaymentParentList = (List<JSONObject>) (Object) repaymentDao.getJSONListByCondition(" AND PARENT_ID=? AND TYPE=0 order by SORT_NO", new Object[]{repaymentFQEntity.getString("id")});
                repaymentFQEntity.put("repaymentParentList", repaymentParentList);
                calRemainingArrears(repaymentFQEntity, repaymentParentList, "1");
            }
        }
        if (null != repaymentRZList && repaymentRZList.size() > 0) {
            for (int i = 0; i < repaymentRZList.size(); i++) {
                JSONObject repaymentRZEntity = repaymentRZList.get(i);
                List<JSONObject> repaymentParentList = (List<JSONObject>) (Object) repaymentDao.getJSONListByCondition(" AND PARENT_ID=? AND TYPE=2 order by SORT_NO", new Object[]{repaymentRZEntity.getString("id")});
                repaymentRZEntity.put("repaymentParentList", repaymentParentList);
                if (contractMainEntity.getHaveDsdf() != 0) {
                    calRemainingArrears(repaymentRZEntity, repaymentParentList, "0");
                } else {
                    repaymentRZEntity.put("everyRemainingArrear", new BigDecimal(0.00));
                    repaymentRZEntity.put("everyOverduePenalty", new BigDecimal(0.00));
                    if (null != repaymentParentList && repaymentParentList.size() > 0) {
                        for (int j = 0; j < repaymentParentList.size(); j++) {
                            repaymentParentList.get(j).put("everyRemainingArrear", new BigDecimal(0.00));
                            repaymentParentList.get(j).put("everyOverduePenalty", new BigDecimal(0.00));
                        }

                    }
                }
            }
        }
        if (null != repaymentRZDBList && repaymentRZDBList.size() > 0) {
            for (int i = 0; i < repaymentRZDBList.size(); i++) {
                JSONObject repaymentRZDBEntity = repaymentRZDBList.get(i);
                List<JSONObject> repaymentParentList = (List<JSONObject>) (Object) repaymentDao.getJSONListByCondition(" AND PARENT_ID=? AND TYPE=4 order by SORT_NO", new Object[]{repaymentRZDBEntity.getString("id")});
                repaymentRZDBEntity.put("repaymentParentList", repaymentParentList);
                if (contractMainEntity.getHaveDsdf() != 0) {
                    calRemainingArrears(repaymentRZDBEntity, repaymentParentList, "0");
                } else {
                    repaymentRZDBEntity.put("everyRemainingArrear", new BigDecimal(0.00));
                    repaymentRZDBEntity.put("everyOverduePenalty", new BigDecimal(0.00));
                    if (null != repaymentParentList && repaymentParentList.size() > 0) {
                        for (int j = 0; j < repaymentParentList.size(); j++) {
                            repaymentParentList.get(j).put("everyRemainingArrear", new BigDecimal(0.00));
                            repaymentParentList.get(j).put("everyOverduePenalty", new BigDecimal(0.00));
                        }

                    }
                }
            }

        }

        if (null != financingRZList && financingRZList.size() > 0) {
            for (int i = 0; i < financingRZList.size(); i++) {
                JSONObject financingEntity = financingRZList.get(i);
                List<JSONObject> repaymentParentList = (List<JSONObject>) (Object) financingDao.getJSONListByCondition(" AND PARENT_ID=? AND TYPE=2  order by SORT_NO", new Object[]{financingEntity.getString("id")});
                financingEntity.put("repaymentParentList", repaymentParentList);
                calRemainingArrears(financingEntity, repaymentParentList);
            }
        }
        if (null != financingRZDBList && financingRZDBList.size() > 0) {
            for (int i = 0; i < financingRZDBList.size(); i++) {
                JSONObject financingEntity = financingRZDBList.get(i);
                List<JSONObject> repaymentParentList = (List<JSONObject>) (Object) financingDao.getJSONListByCondition(" AND PARENT_ID=? AND TYPE=4  order by SORT_NO", new Object[]{financingEntity.getString("id")});
                financingEntity.put("repaymentParentList", repaymentParentList);
                calRemainingArrears(financingEntity, repaymentParentList);
            }
        }
        JSONObject result = new JSONObject();
        result.put("main", contractMainEntity);
        result.put("repaymentFQList", repaymentFQList);
        result.put("repaymentDKList", repaymentDKList);
        result.put("repaymentRZList", repaymentRZList);
        result.put("repaymentRZDBList", repaymentRZDBList);
        result.put("repaymentSFList", repaymentSFList);
        result.put("financingRZList", financingRZList);
        result.put("financingRZDBList", financingRZDBList);
        return result;

    }

    //保存冲抵list
    @Override
    public JSONObject saveAcountRepaymentListById(String jsonData) {
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        JSONArray repaymentFQList = new JSONArray();
        JSONArray repaymentDKList = new JSONArray();
        JSONArray repaymentRZList = new JSONArray();
        JSONArray repaymentRZDBList = new JSONArray();
        JSONArray financingRZList = new JSONArray();
        JSONArray financingRZDBList = new JSONArray();
        JSONArray repaymentSFList = new JSONArray();
        JSONObject main = JSON.parseObject(jsonPalams.getString("main"));
        String repayDate = jsonPalams.getString("repayDate");
        String createUserId = jsonPalams.getString("createUserId");
        String createUserName = jsonPalams.getString("createUserName");
        String nowDate = DateUtils.nowDayByString(contractMainDao.getCurrentTime());
        ContractMainEntity contractMainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(main.getString("id"));
        contractMainEntity.setAccountBalance(jsonPalams.getBigDecimal("canUseMoney"));
        if (contractMainEntity.getHaveOverdue() != 2) {
            contractMainEntity.setHaveOverdue(0);
            contractMainEntity.setHaveOverdueNo(-6);
        }
        contractMainDao.update(contractMainEntity);
        repaymentFQList = JSONArray.fromObject(jsonPalams.getJSONArray("repaymentFQList"));
        repaymentDKList = JSONArray.fromObject(jsonPalams.getJSONArray("repaymentDKList"));
        repaymentRZList = JSONArray.fromObject(jsonPalams.getJSONArray("repaymentRZList"));
        repaymentRZDBList = JSONArray.fromObject(jsonPalams.getJSONArray("repaymentRZDBList"));
        repaymentSFList = JSONArray.fromObject(jsonPalams.getJSONArray("repaymentSFList"));
        financingRZList = JSONArray.fromObject(jsonPalams.getJSONArray("financingRZList"));
        financingRZDBList = JSONArray.fromObject(jsonPalams.getJSONArray("financingRZDBList"));
        Integer havaDsdf = contractMainEntity.getHaveDsdf();
        saveRepaymentList(repaymentFQList, repayDate, createUserId, createUserName, 0, nowDate);
        saveRepaymentList(repaymentDKList, repayDate, createUserId, createUserName, 1, nowDate);
        saveRepaymentList(repaymentSFList, repayDate, createUserId, createUserName, 3, nowDate);
        if (havaDsdf != 0) {
            saveRepaymentList(repaymentRZList, repayDate, createUserId, createUserName, 2, nowDate);
            saveRepaymentList(repaymentRZDBList, repayDate, createUserId, createUserName, 4, nowDate);
        }
        saveFinancingList(financingRZList, repayDate, createUserId, createUserName, 2, nowDate);
        saveFinancingList(financingRZDBList, repayDate, createUserId, createUserName, 4, nowDate);
        JSONObject result = new JSONObject();
        result.put("true", "true");
        JSONObject main1 = getAcountRepaymentById(contractMainEntity.getId());
        saveOver(main1.toJSONString());
        return result;

    }

    //将快到期保存看是否逾期
    @Override
    public JSONObject saveOverByRepayment(){
        List<JSONObject> jsonObjects= repaymentDao.getRepaymentDateBefore();
        if (jsonObjects!=null&&jsonObjects.size()>0){
            for (int i=0;i<jsonObjects.size();i++){
                JSONObject main = getContract(jsonObjects.get(i).getString("mainId"));
                receivableSaveOver(main.toJSONString());
            }
        }
        JSONObject result = new JSONObject();
        result.put("true", "true");
        return result;
    }

    //保存逾期
    public void saveOver(String jsonData) {
        JSONObject jsonPalams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        JSONArray repaymentFQList = new JSONArray();
        JSONArray repaymentDKList = new JSONArray();
        JSONArray repaymentRZList = new JSONArray();
        JSONArray repaymentRZDBList = new JSONArray();
        JSONArray financingRZList = new JSONArray();
        JSONArray financingRZDBList = new JSONArray();
        JSONArray repaymentSFList = new JSONArray();
        JSONObject main = JSON.parseObject(jsonPalams.getString("main"));
        String repayDate = jsonPalams.getString("repayDate");
        String createUserId = jsonPalams.getString("createUserId");
        String createUserName = jsonPalams.getString("createUserName");
        String nowDate = DateUtils.nowDayByString(contractMainDao.getCurrentTime());
        ContractMainEntity contractMainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(main.getString("id"));
        contractMainEntity.setAccountBalance(jsonPalams.getBigDecimal("canUseMoney"));
        if (contractMainEntity.getHaveOverdue() != 2) {
            contractMainEntity.setHaveOverdue(0);
            contractMainEntity.setHaveOverdueNo(-6);
        }
        contractMainDao.update(contractMainEntity);
        repaymentFQList = JSONArray.fromObject(jsonPalams.getJSONArray("repaymentFQList"));
        repaymentDKList = JSONArray.fromObject(jsonPalams.getJSONArray("repaymentDKList"));
        repaymentRZList = JSONArray.fromObject(jsonPalams.getJSONArray("repaymentRZList"));
        repaymentRZDBList = JSONArray.fromObject(jsonPalams.getJSONArray("repaymentRZDBList"));
        repaymentSFList = JSONArray.fromObject(jsonPalams.getJSONArray("repaymentSFList"));
        financingRZList = JSONArray.fromObject(jsonPalams.getJSONArray("financingRZList"));
        financingRZDBList = JSONArray.fromObject(jsonPalams.getJSONArray("financingRZDBList"));
        Integer havaDsdf = contractMainEntity.getHaveDsdf();
        saveRepaymentList(repaymentFQList, repayDate, createUserId, createUserName, 0, nowDate);
        saveRepaymentList(repaymentDKList, repayDate, createUserId, createUserName, 1, nowDate);
        saveRepaymentList(repaymentSFList, repayDate, createUserId, createUserName, 3, nowDate);
        if (havaDsdf != 0) {
            saveRepaymentList(repaymentRZList, repayDate, createUserId, createUserName, 2, nowDate);
            saveRepaymentList(repaymentRZDBList, repayDate, createUserId, createUserName, 4, nowDate);
        }
        saveFinancingList(financingRZList, repayDate, createUserId, createUserName, 2, nowDate);
        saveFinancingList(financingRZDBList, repayDate, createUserId, createUserName, 4, nowDate);

    }

    public void receivableSaveOver(String jsonData) {
        ContractEntity model = JSON.toJavaObject(JSON.parseObject(jsonData), ContractEntity.class);
        //获取所有表的信息
        ContractMainEntity contractMainEntity = model.getMain();//主表信息
        List<RepaymentEntity> repaymentaDKEntityList = model.getRepaymentDKList();//垫款条款
        List<RepaymentEntity> repaymentaFQEntityList = model.getRepaymentFQList();//内部分期
        List<RepaymentEntity> repaymentaRZEntityList = model.getRepaymentRZList();//融资分期
        List<FinancingEntity> financingRZEntityList = model.getFinancingRZList();//融资分期款跟踪
        List<FinancingEntity> financingRZDBEntityList = model.getFinancingRZDBList();//融资分期款跟踪
        List<RepaymentEntity> repaymentaRZDBEntityList = model.getRepaymentRZDBList();//融资分期
        List<RepaymentEntity> repaymentaSFEntityList = model.getRepaymentSFList();//首付款信息
        String mainId = contractMainEntity.getId();//主表的ID
        //首付款信息
        if (null != repaymentaSFEntityList && repaymentaSFEntityList.size() > 0) {
            getRepaymentSave(repaymentaSFEntityList, mainId, model.getCreateUserId(), model.getCreateUserName());
        }

        //内部分期
        if (null != repaymentaFQEntityList && repaymentaFQEntityList.size() > 0) {
            getRepaymentSaveOvRe(repaymentaFQEntityList);
        }
        //融资分期
        if (null != repaymentaRZEntityList && repaymentaRZEntityList.size() > 0) {
            getRepaymentSaveOvRe(repaymentaRZEntityList);
        }
        //融资分期款跟踪

        if (null != financingRZEntityList && financingRZEntityList.size() > 0) {
            getRepaymentSaveOvReFn(financingRZEntityList);
        }
        //融资分期款跟踪

        if (null != financingRZDBEntityList && financingRZDBEntityList.size() > 0) {
            getRepaymentSaveOvReFn(financingRZDBEntityList);
        }
        //融资分期
        if (null != repaymentaRZDBEntityList && repaymentaRZDBEntityList.size() > 0) {
            getRepaymentSaveOvRe(repaymentaRZDBEntityList);
        }
        //首付款垫款信息
        if (contractMainEntity.getHaveRepayment() == 1) {
            if (null != repaymentaDKEntityList && repaymentaDKEntityList.size() > 0) {
                getRepaymentSave(repaymentaDKEntityList, mainId, model.getCreateUserId(), model.getCreateUserName());
            }
        }
        JSONObject main = getAcountRepaymentById(contractMainEntity.getId());
        saveOver(main.toJSONString());
    }

    @Override
    public JSONObject selectContractAccountById(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String repayDate = jsonParams.getString("repayDate");
        String mainId = jsonParams.getString("mainId");
        String condition = "AND MAIN_ID = '" + mainId + "'\n" +
                "AND (\n" +
                "\tREMAINING_ARREARS IS NOT NULL\n" +
                "\tAND REMAINING_ARREARS != 0.00\n" +
                ")\n" +
                "OR (\n" +
                "\tREPAYMENT_DATE > '" + repayDate + "'\n" +
                "\tAND MAIN_ID = '" + mainId + "'\n" +
                ")\n" +
                "ORDER BY\n" +
                "\tREPAYMENT_DATE";
        List<JSONObject> repaymentList = repaymentDao.getJSONListByCondition(condition, new Object[]{});
        JSONObject result = new JSONObject();
        result.put("repaymentList", repaymentList);
        return result;
    }

    @Override
    public List<JSONObject> interestLook(String jsonData) {
        return repaymentDao.interestLook(jsonData);
    }

    @Override
    public JSONObject updateContractAccountMoney(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String repayDate = jsonParams.getString("repayDate");
        String id = jsonParams.getString("id");
        String type = jsonParams.getString("type");
        if (type.equals("1")) {
            RepaymentEntity newRepaymentEntity = new RepaymentEntity();
            RepaymentEntity repaymentEntity = (RepaymentEntity) repaymentDao.getIBaseEntityById(id);
            newRepaymentEntity.setRepaymentAmount(repaymentEntity.getRemainingArrears());
            newRepaymentEntity.setRepaymentDate(repayDate);
            if (repaymentEntity.getParentId().equals("0")) {
                newRepaymentEntity.setParentId(repaymentEntity.getId());
            }
            ;
            repaymentEntity.setRemainingArrears(new BigDecimal(0.00));
            repaymentDao.update(repaymentEntity);
        }
        return null;
    }

    //应收保存方法
    @Override
    public JSONObject receivable(String jsonData) {
        ContractEntity model = JSON.toJavaObject(JSON.parseObject(jsonData), ContractEntity.class);
        List<JSONObject> jsonObjectList = new ArrayList<>();
        //获取所有表的信息
        ContractMainEntity contractMainEntity = model.getMain();//买卖双方及担保方信息
        List<RepaymentEntity> repaymentaDKEntityList = model.getRepaymentDKList();//垫款条款
        List<RepaymentEntity> repaymentaFQEntityList = model.getRepaymentFQList();//内部分期
        List<RepaymentEntity> repaymentaRZEntityList = model.getRepaymentRZList();//融资分期
        List<FinancingEntity> financingRZEntityList = model.getFinancingRZList();//融资分期款跟踪
        List<FinancingEntity> financingRZDBEntityList = model.getFinancingRZDBList();//融资分期款跟踪
        List<RepaymentEntity> repaymentaRZDBEntityList = model.getRepaymentRZDBList();//融资分期
        List<RepaymentEntity> repaymentaSFEntityList = model.getRepaymentSFList();//首付款信息
        List<RepaymentEntity> repaymentFQFirstList = model.getRepaymentFQFirstList();//首付款信息
        List<CollectionEntity> collectionList = model.getCollectionList();//催款记录

        String mainId = contractMainEntity.getId();//主表的ID
        boolean flag = true;
        //修改合同，先级联删除现有的所有合同，再添加
        repaymentDao.removeByCondition("AND MAIN_ID = ? ", new String[]{mainId});
        financingDao.removeByCondition("AND MAIN_ID = ? ", new String[]{mainId});
        collectionDao.removeByCondition("  AND MAIN_ID =?", new String[]{mainId});

        //更新主表信息
        ContractMainEntity mainEntitys = (ContractMainEntity) contractMainDao.getIBaseEntityById(mainId);
        if (mainEntitys.getHaveOverdue() != 2) {
            contractMainEntity.setHaveOverdue(0);
            contractMainEntity.setHaveOverdueNo(-6);
            contractMainDao.update(contractMainEntity);
        }
        String nowDate = DateUtils.nowDateByString(contractMainDao.getCurrentTime());
        //首付款信息(销售台账)
        if (null != repaymentaSFEntityList && repaymentaSFEntityList.size() > 0) {
            for (int i = 0; i < repaymentaSFEntityList.size(); i++) {
                BigDecimal yjSum = new BigDecimal("0.00");
                BigDecimal yqSum = new BigDecimal("0.00");
                String dateTime = "";
                RepaymentEntity repaymentEntity = repaymentaSFEntityList.get(i);
                //还款日期不为空则添加
                //模块0-内部分期/1-垫款/2-融资分期/3-首付款信息
                repaymentaSFEntityList.get(i).setType(3);
                repaymentaSFEntityList.get(i).setMainId(mainId);
                repaymentaSFEntityList.get(i).setSortNo(i);
                repaymentDao.add(repaymentaSFEntityList.get(i));
                yjSum = yjSum.add(repaymentEntity.getRemainingArrears());
                yqSum = yqSum.add(repaymentEntity.getRepaymentAmount());
                dateTime = repaymentEntity.getActualRepaymentDate();

                if (repaymentEntity.getRepaymentParentList() != null && repaymentEntity.getRepaymentParentList().size() > 0) {
                    for (int j = 0; j < repaymentEntity.getRepaymentParentList().size(); j++) {
                        if (!StringUtils.isBlank(repaymentEntity.getRepaymentParentList().get(j).getRepaymentDate())) {
                            repaymentEntity.getRepaymentParentList().get(j).setMainId(mainId);
                            repaymentEntity.getRepaymentParentList().get(j).setType(3);
                            repaymentEntity.getRepaymentParentList().get(j).setSortNo(j);
                            repaymentEntity.getRepaymentParentList().get(j).setParentId(repaymentEntity.getId());
                            repaymentDao.add(repaymentEntity.getRepaymentParentList().get(j));
                            yjSum = yjSum.add(repaymentEntity.getRepaymentParentList().get(j).getRemainingArrears());
                            yqSum = yqSum.add(repaymentEntity.getRepaymentParentList().get(j).getRepaymentAmount());
                            dateTime = repaymentEntity.getRepaymentParentList().get(j).getActualRepaymentDate();
                        }
                    }
                }
                //判断是否逾期
                ContractMainEntity mainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(contractMainEntity.getId());
                if (repaymentEntity.getTotal().compareTo(yqSum) > 0 &&
                        dateTime.compareTo(repaymentEntity.getRepaymentDate()) >= 0) {
                    if (mainEntity.getHaveOverdue() == 0) {
                        Integer haveOverdueNo = DateUtils.getDaySub(repaymentEntity.getRepaymentDate(), dateTime);
                        if (haveOverdueNo != -6 && haveOverdueNo > 0) {
                            mainEntity.setHaveOverdue(1);
                            flag = false;
                            mainEntity.setHaveOverdueNo(haveOverdueNo);
                            contractMainDao.update(mainEntity);
                        } else {
                            if (repaymentEntity.getRepaymentDate().compareTo(nowDate) <= 0) {
                                Integer overdueNo = DateUtils.getDaySub(nowDate, repaymentEntity.getRepaymentDate());
                                mainEntity.setHaveOverdue(1);
                                flag = false;
                                mainEntity.setHaveOverdueNo(overdueNo);
                                contractMainDao.update(mainEntity);
                            }
                        }
                    }
                } else {
                    if (mainEntity.getHaveOverdue() != 2) {
                        if (flag) {
                            mainEntity.setHaveOverdue(0);
                            mainEntity.setHaveOverdueNo(-6);
                            contractMainDao.update(mainEntity);

                        }
                    }
                }
            }
        }
        //判断是否为垫款->插入分期表
        if (contractMainEntity.getHaveRepayment() == 1) {
            for (int i = 0; i < repaymentaDKEntityList.size(); i++) {
                BigDecimal yjSum = new BigDecimal("0.00");
                BigDecimal yqSum = new BigDecimal("0.00");
                String dateTime = "";
                RepaymentEntity repaymentEntity = repaymentaDKEntityList.get(i);
                //还款日期不为空则添加
                if (!StringUtils.isBlank(repaymentEntity.getRepaymentDate())) {
                    repaymentEntity.setMainId(mainId);
                    repaymentEntity.setType(1);
                    repaymentEntity.setSortNo(i);
                    repaymentEntity.setTotal(repaymentEntity.getInterest().add(repaymentEntity.getPrincipal()));
                    repaymentDao.add(repaymentEntity);
                    yjSum = yjSum.add(repaymentEntity.getRemainingArrears());
                    yqSum = yqSum.add(repaymentEntity.getRepaymentAmount());
                    dateTime = repaymentEntity.getActualRepaymentDate();
                }
                if (repaymentEntity.getRepaymentParentList() != null && repaymentEntity.getRepaymentParentList().size() > 0) {
                    for (int j = 0; j < repaymentEntity.getRepaymentParentList().size(); j++) {
                        if (!StringUtils.isBlank(repaymentEntity.getRepaymentParentList().get(j).getRepaymentDate())) {
                            repaymentEntity.getRepaymentParentList().get(j).setMainId(mainId);
                            repaymentEntity.getRepaymentParentList().get(j).setType(1);
                            repaymentEntity.getRepaymentParentList().get(j).setSortNo(j);
                            repaymentEntity.getRepaymentParentList().get(j).setParentId(repaymentEntity.getId());
                            repaymentDao.add(repaymentEntity.getRepaymentParentList().get(j));
                            yjSum = yjSum.add(repaymentEntity.getRepaymentParentList().get(j).getRemainingArrears());
                            yqSum = yqSum.add(repaymentEntity.getRepaymentParentList().get(j).getRepaymentAmount());
                            dateTime = repaymentEntity.getRepaymentParentList().get(j).getActualRepaymentDate();

                        }
                    }
                }
                //判断是否逾期
                ContractMainEntity mainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(contractMainEntity.getId());

                if (repaymentEntity.getTotal().compareTo(yqSum) > 0 &&
                        dateTime.compareTo(repaymentEntity.getRepaymentDate()) >= 0) {

                    if (mainEntity.getHaveOverdue() == 0) {
                        Integer haveOverdueNo = DateUtils.getDaySub(repaymentEntity.getRepaymentDate(), dateTime);
                        if (haveOverdueNo != -6 && haveOverdueNo > 0) {
                            mainEntity.setHaveOverdue(1);
                            flag = false;
                            mainEntity.setHaveOverdueNo(haveOverdueNo);
                            contractMainDao.update(mainEntity);
                        } else {
                            if (repaymentEntity.getRepaymentDate().compareTo(nowDate) <= 0) {
                                Integer overdueNo = DateUtils.getDaySub(nowDate, repaymentEntity.getRepaymentDate());
                                flag = false;
                                mainEntity.setHaveOverdue(1);
                                mainEntity.setHaveOverdueNo(overdueNo);
                                contractMainDao.update(mainEntity);
                            }
                        }
                    }
                } else {
                    if (mainEntity.getHaveOverdue() != 2) {
                        if (flag) {
                            mainEntity.setHaveOverdue(0);
                            mainEntity.setHaveOverdueNo(-6);
                            contractMainDao.update(mainEntity);

                        }
                    }
                }
            }
        }
        //判断购买方式是否为内部分期->插入分期表
        if (contractMainEntity.getBuyType().equals("内部分期")) {
            for (int i = 0; i < repaymentaFQEntityList.size(); i++) {
                BigDecimal yjSum = new BigDecimal("0.00");
                BigDecimal yqSum = new BigDecimal("0.00");
                String dateTime = "";
                RepaymentEntity repaymentEntity = repaymentaFQEntityList.get(i);
                //还款日期不为空则添加
                if (!StringUtils.isBlank(repaymentEntity.getRepaymentDate())) {
                    repaymentEntity.setType(0);
                    repaymentEntity.setMainId(mainId);
                    repaymentEntity.setSortNo(i);
                    repaymentEntity.setTotal(repaymentaFQEntityList.get(i).getInterest().add(repaymentaFQEntityList.get(i).getPrincipal()));
                    repaymentDao.add(repaymentEntity);
                    yjSum = yjSum.add(repaymentEntity.getRemainingArrears());
                    yqSum = yqSum.add(repaymentEntity.getRepaymentAmount());
                    dateTime = repaymentEntity.getActualRepaymentDate();

                }
                if (repaymentEntity.getRepaymentParentList() != null && repaymentEntity.getRepaymentParentList().size() > 0) {
                    for (int j = 0; j < repaymentEntity.getRepaymentParentList().size(); j++) {
                        if (!StringUtils.isBlank(repaymentEntity.getRepaymentParentList().get(j).getRepaymentDate())) {
                            repaymentEntity.getRepaymentParentList().get(j).setMainId(mainId);
                            repaymentEntity.getRepaymentParentList().get(j).setType(0);
                            repaymentEntity.getRepaymentParentList().get(j).setSortNo(j);
                            repaymentEntity.getRepaymentParentList().get(j).setParentId(repaymentEntity.getId());
                            repaymentDao.add(repaymentEntity.getRepaymentParentList().get(j));
                            yjSum = yjSum.add(repaymentEntity.getRepaymentParentList().get(j).getRemainingArrears());
                            yqSum = yqSum.add(repaymentEntity.getRepaymentParentList().get(j).getRepaymentAmount());
                            dateTime = repaymentEntity.getRepaymentParentList().get(j).getActualRepaymentDate();

                        }
                    }
                }
                //判断是否逾期
                ContractMainEntity mainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(contractMainEntity.getId());

                if (repaymentEntity.getTotal().compareTo(yqSum) > 0 &&
                        dateTime.compareTo(repaymentEntity.getRepaymentDate()) >= 0) {

                    if (mainEntity.getHaveOverdue() == 0) {
                        Integer haveOverdueNo = DateUtils.getDaySub(repaymentEntity.getRepaymentDate(), dateTime);
                        if (haveOverdueNo != -6 && haveOverdueNo > 0) {
                            mainEntity.setHaveOverdue(1);
                            flag = false;
                            mainEntity.setHaveOverdueNo(haveOverdueNo);
                            contractMainDao.update(mainEntity);
                        } else {
                            if (repaymentEntity.getRepaymentDate().compareTo(nowDate) <= 0) {
                                Integer overdueNo = DateUtils.getDaySub(nowDate, repaymentEntity.getRepaymentDate());
                                mainEntity.setHaveOverdue(1);
                                flag = false;
                                mainEntity.setHaveOverdueNo(overdueNo);
                                contractMainDao.update(mainEntity);
                            }
                        }
                    }
                } else {
                    if (mainEntity.getHaveOverdue() != 2) {
                        if (flag) {
                            mainEntity.setHaveOverdue(0);
                            mainEntity.setHaveOverdueNo(-6);
                            contractMainDao.update(mainEntity);

                        }
                    }
                }
            }
        }
        //判断购买方式是否为内部分期 并且有分期首付款分期 ->插入分期表
        if (contractMainEntity.getBuyType().equals("内部分期") && contractMainEntity.getHaveFQFirst() == 1) {

            for (int i = 0; i < repaymentFQFirstList.size(); i++) {
                BigDecimal yjSum = new BigDecimal("0.00");
                BigDecimal yqSum = new BigDecimal("0.00");
                String dateTime = "";
                RepaymentEntity repaymentEntity = repaymentFQFirstList.get(i);
                //还款日期不为空则添加
                if (!StringUtils.isBlank(repaymentEntity.getRepaymentDate())) {
                    repaymentEntity.setType(5);
                    repaymentEntity.setMainId(mainId);
                    repaymentEntity.setSortNo(i);
                    repaymentEntity.setTotal(repaymentFQFirstList.get(i).getPrincipal());
                    repaymentDao.add(repaymentEntity);
                    yjSum = yjSum.add(repaymentEntity.getRemainingArrears());
                    yqSum = yqSum.add(repaymentEntity.getRepaymentAmount());
                    dateTime = repaymentEntity.getActualRepaymentDate();

                }
                if (repaymentEntity.getRepaymentParentList() != null && repaymentEntity.getRepaymentParentList().size() > 0) {
                    for (int j = 0; j < repaymentEntity.getRepaymentParentList().size(); j++) {
                        if (!StringUtils.isBlank(repaymentEntity.getRepaymentParentList().get(j).getRepaymentDate())) {
                            repaymentEntity.getRepaymentParentList().get(j).setMainId(mainId);
                            repaymentEntity.getRepaymentParentList().get(j).setType(5);
                            repaymentEntity.getRepaymentParentList().get(j).setSortNo(j);
                            repaymentEntity.getRepaymentParentList().get(j).setParentId(repaymentEntity.getId());
                            repaymentDao.add(repaymentEntity.getRepaymentParentList().get(j));
                            yjSum = yjSum.add(repaymentEntity.getRepaymentParentList().get(j).getRemainingArrears());
                            yqSum = yqSum.add(repaymentEntity.getRepaymentParentList().get(j).getRepaymentAmount());
                            dateTime = repaymentEntity.getRepaymentParentList().get(j).getActualRepaymentDate();
                        }
                    }
                }
                //判断是否逾期
                ContractMainEntity mainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(contractMainEntity.getId());

                if (repaymentEntity.getTotal().compareTo(yqSum) > 0 &&
                        dateTime.compareTo(repaymentEntity.getRepaymentDate()) >= 0) {


                    if (mainEntity.getHaveOverdue() == 0) {
                        Integer haveOverdueNo = DateUtils.getDaySub(repaymentEntity.getRepaymentDate(), dateTime);
                        if (haveOverdueNo != -6 && haveOverdueNo > 0) {
                            mainEntity.setHaveOverdue(1);
                            flag = false;
                            mainEntity.setHaveOverdueNo(haveOverdueNo);
                            contractMainDao.update(mainEntity);
                        } else {
                            if (repaymentEntity.getRepaymentDate().compareTo(nowDate) <= 0) {
                                Integer overdueNo = DateUtils.getDaySub(nowDate, repaymentEntity.getRepaymentDate());
                                mainEntity.setHaveOverdue(1);
                                flag = false;
                                mainEntity.setHaveOverdueNo(overdueNo);
                                contractMainDao.update(mainEntity);
                            }
                        }
                    }
                } else {
                    if (mainEntity.getHaveOverdue() != 2) {
                        if (flag) {
                            mainEntity.setHaveOverdue(0);
                            mainEntity.setHaveOverdueNo(-6);
                            contractMainDao.update(mainEntity);
                        }
                    }
                }

            }
        }
        //判断购买方式是否为融资租赁->插入分期表
        if (contractMainEntity.getBuyType().equals("融资租赁")) {
            //融资分期跟踪
            for (int i = 0; i < financingRZEntityList.size(); i++) {
                FinancingEntity financingEntity = financingRZEntityList.get(i);
                if (!StringUtils.isBlank(financingEntity.getFinancingDate())) {
                    financingEntity.setMainId(mainId);
                    financingEntity.setSortNo(i);
                    financingDao.add(financingEntity);
                }
            }
            for (int i = 0; i < repaymentaRZEntityList.size(); i++) {
                BigDecimal yjSum = new BigDecimal("0.00");
                BigDecimal yqSum = new BigDecimal("0.00");
                String dateTime = "";
                RepaymentEntity repaymentEntity = repaymentaRZEntityList.get(i);
                //还款日期不为空则添加
                if (!StringUtils.isBlank(repaymentEntity.getRepaymentDate())) {
                    repaymentEntity.setType(2);
                    repaymentEntity.setMainId(mainId);
                    repaymentEntity.setSortNo(i);
                    repaymentDao.add(repaymentEntity);
                    yjSum = yjSum.add(repaymentEntity.getRemainingArrears());
                    yqSum = yqSum.add(repaymentEntity.getRepaymentAmount());
                    dateTime = repaymentEntity.getActualRepaymentDate();
                }

                if (repaymentEntity.getRepaymentParentList() != null && repaymentEntity.getRepaymentParentList().size() > 0) {
                    for (int j = 0; j < repaymentEntity.getRepaymentParentList().size(); j++) {
                        if (!StringUtils.isBlank(repaymentEntity.getRepaymentParentList().get(j).getRepaymentDate())) {
                            repaymentEntity.getRepaymentParentList().get(j).setMainId(mainId);
                            repaymentEntity.getRepaymentParentList().get(j).setType(2);
                            repaymentEntity.getRepaymentParentList().get(j).setSortNo(j);
                            repaymentEntity.getRepaymentParentList().get(j).setParentId(repaymentEntity.getId());
                            repaymentDao.add(repaymentEntity.getRepaymentParentList().get(j));
                            yjSum = yjSum.add(repaymentEntity.getRepaymentParentList().get(j).getRemainingArrears());
                            yqSum = yqSum.add(repaymentEntity.getRepaymentParentList().get(j).getRepaymentAmount());
                            dateTime = repaymentEntity.getRepaymentParentList().get(j).getActualRepaymentDate();
                        }
                    }
                }
                //判断是否逾期
                ContractMainEntity mainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(contractMainEntity.getId());

                if (repaymentEntity.getContractRepaymentAmount().compareTo(yqSum) > 0 &&
                        dateTime.compareTo(repaymentEntity.getRepaymentDate()) >= 0) {

                    if (mainEntity.getHaveOverdue() == 0) {
                        Integer haveOverdueNo = DateUtils.getDaySub(repaymentEntity.getRepaymentDate(), dateTime);
                        if (haveOverdueNo != -6 && haveOverdueNo > 0) {
                            mainEntity.setHaveOverdue(1);
                            flag = false;
                            mainEntity.setHaveOverdueNo(haveOverdueNo);
                            contractMainDao.update(mainEntity);
                        } else {
                            if (repaymentEntity.getRepaymentDate().compareTo(nowDate) <= 0) {
                                Integer overdueNo = DateUtils.getDaySub(nowDate, repaymentEntity.getRepaymentDate());
                                mainEntity.setHaveOverdue(1);
                                flag = false;
                                mainEntity.setHaveOverdueNo(overdueNo);
                                contractMainDao.update(mainEntity);
                            }
                        }
                    }
                } else {
                    if (mainEntity.getHaveOverdue() != 2) {
                        if (flag) {
                            mainEntity.setHaveOverdue(0);
                            mainEntity.setHaveOverdueNo(-6);
                            contractMainDao.update(mainEntity);
                        }
                    }
                }
            }
        }
        //判断购买方式是否为融资租赁打包->插入分期表
        if (contractMainEntity.getBuyType().equals("融资租赁打包")) {
            //融资分期跟踪
            for (int i = 0; i < financingRZDBEntityList.size(); i++) {
                FinancingEntity financingEntity = financingRZDBEntityList.get(i);
                if (!StringUtils.isBlank(financingEntity.getFinancingDate())) {
                    financingEntity.setMainId(mainId);
                    financingEntity.setSortNo(i);
                    financingDao.add(financingEntity);
                }
            }
            for (int i = 0; i < repaymentaRZDBEntityList.size(); i++) {
                BigDecimal yjSum = new BigDecimal("0.00");
                BigDecimal yqSum = new BigDecimal("0.00");
                String dateTime = "";
                RepaymentEntity repaymentEntity = repaymentaRZDBEntityList.get(i);
                //还款日期不为空则添加
                if (!StringUtils.isBlank(repaymentEntity.getRepaymentDate())) {
                    repaymentEntity.setType(4);
                    repaymentEntity.setMainId(mainId);
                    repaymentEntity.setSortNo(i);
                    repaymentDao.add(repaymentEntity);
                    yjSum = yjSum.add(repaymentEntity.getRemainingArrears());
                    yqSum = yqSum.add(repaymentEntity.getRepaymentAmount());
                    dateTime = repaymentEntity.getActualRepaymentDate();
                }
                if (repaymentEntity.getRepaymentParentList() != null && repaymentEntity.getRepaymentParentList().size() > 0) {
                    for (int j = 0; j < repaymentEntity.getRepaymentParentList().size(); j++) {
                        if (!StringUtils.isBlank(repaymentEntity.getRepaymentParentList().get(j).getRepaymentDate())) {
                            repaymentEntity.getRepaymentParentList().get(j).setMainId(mainId);
                            repaymentEntity.getRepaymentParentList().get(j).setType(4);
                            repaymentEntity.getRepaymentParentList().get(j).setSortNo(j);
                            repaymentEntity.getRepaymentParentList().get(j).setParentId(repaymentEntity.getId());
                            repaymentDao.add(repaymentEntity.getRepaymentParentList().get(j));
                            yjSum = yjSum.add(repaymentEntity.getRepaymentParentList().get(j).getRemainingArrears());
                            yqSum = yqSum.add(repaymentEntity.getRepaymentParentList().get(j).getRepaymentAmount());
                            dateTime = repaymentEntity.getRepaymentParentList().get(j).getActualRepaymentDate();
                        }
                    }
                }
                ContractMainEntity mainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(contractMainEntity.getId());

                //判断是否逾期
                if (repaymentEntity.getContractRepaymentAmount().compareTo(yqSum) > 0 &&
                        dateTime.compareTo(repaymentEntity.getRepaymentDate()) >= 0) {

                    if (mainEntity.getHaveOverdue() == 0) {
                        Integer haveOverdueNo = DateUtils.getDaySub(repaymentEntity.getRepaymentDate(), dateTime);
                        if (haveOverdueNo != -6 && haveOverdueNo > 0) {
                            mainEntity.setHaveOverdue(1);
                            flag = false;
                            mainEntity.setHaveOverdueNo(haveOverdueNo);
                            contractMainDao.update(mainEntity);
                        } else {
                            if (repaymentEntity.getRepaymentDate().compareTo(nowDate) <= 0) {
                                Integer overdueNo = DateUtils.getDaySub(nowDate, repaymentEntity.getRepaymentDate());
                                mainEntity.setHaveOverdue(1);
                                flag = false;
                                mainEntity.setHaveOverdueNo(overdueNo);
                                contractMainDao.update(mainEntity);
                            }
                        }
                    }
                } else {
                    if (mainEntity.getHaveOverdue() != 2) {
                        if (flag) {
                            mainEntity.setHaveOverdue(0);
                            mainEntity.setHaveOverdueNo(-6);
                            contractMainDao.update(mainEntity);
                        }
                    }
                }
            }
        }
        //催收记录
        if (null != collectionList && collectionList.size() > 0) {
            for (int i = 0; i < collectionList.size(); i++) {
                CollectionEntity collectionEntity = collectionList.get(i);
                if (StringUtils.isNotEmpty(collectionEntity.getCollection())) {
                    collectionEntity.setMainId(mainId);
                    collectionEntity.setSortNo(i);
                    collectionDao.add(collectionEntity);
                }
            }
        }
        //判断接近还款日期
        String mainIds = "";
        ContractMainEntity mains = (ContractMainEntity) contractMainDao.getIBaseEntityById(mainId);
        if (mains.getHaveOverdue() == 2) {
            List<JSONObject> list = contractMainDao.senderExpireList();
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    mainIds += "'" + list.get(i).getString("mainId") + "',";
                }
            }
            if (mainIds.length() > 0) {
                mainIds = mainIds.substring(0, mainIds.length() - 1);
            }
            if (!mainIds.contains(mainId)) {
                mains.setHaveOverdue(0);
                mains.setHaveOverdueNo(-6);
                contractMainDao.update(mains);
            }
        }
        JSONObject result = new JSONObject();
        result.put("message", jsonObjectList);
        result.put("flag", true);
        return result;
    }

    //查询合格证
    @Override
    public JSONObject getUploadFileByContractId(String jsonData) {
        JSONObject json = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String id=json.getString("contractId");
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("SELECT * FROM v_com_attach WHERE 1=1" + "\n");
        stringBuffer.append("AND moduleId=" + " '" + id + " ' AND ATTACH_MODULE=19");
        List<JSONObject> invoice = contractMainDao.queryForJsonList(stringBuffer.toString(), new Object[]{});
        if (invoice.size() == 0) {
            invoice = new ArrayList<JSONObject>();
        }
        StringBuffer stringBuffer2 = new StringBuffer();
        stringBuffer2.append("SELECT * FROM v_com_attach WHERE 1=1" + "\n");
        stringBuffer2.append("AND moduleId=" + " '" + id + " ' AND ATTACH_MODULE=18");
        List<JSONObject> certificate = contractMainDao.queryForJsonList(stringBuffer2.toString(), new Object[]{});
        if (certificate.size() == 0) {
            certificate = new ArrayList<JSONObject>();
        }
        StringBuffer stringBuffer3 = new StringBuffer();
        stringBuffer3.append("SELECT * FROM v_com_attach WHERE 1=1" + "\n");
        stringBuffer3.append("AND moduleId=" + " '" + id + " ' AND ATTACH_MODULE=20");
        List<JSONObject> ownershipTransfer = contractMainDao.queryForJsonList(stringBuffer3.toString(), new Object[]{});
        if (ownershipTransfer.size() == 0) {
            ownershipTransfer = new ArrayList<JSONObject>();
        }
        JSONObject result=new JSONObject();
        result.put("invoice",invoice);
        result.put("certificate",certificate);
        result.put("ownershipTransfer",ownershipTransfer);
        return result;
    }

    @Override
    public JSONObject saveUploadFile(String jsonData) {
        JSONObject json = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String mainId=json.getString("contractId");
        String certificate =json.getString("certificate");
        List<JSONObject> certificateList = (List<JSONObject>) JSONArray.toCollection(JSONArray.fromObject(certificate), JSONObject.class);

        String invoice =json.getString("invoice");
        List<JSONObject> invoiceList = (List<JSONObject>) JSONArray.toCollection(JSONArray.fromObject(invoice), JSONObject.class);

        String ownershipTransfer =json.getString("ownershipTransfer");
        List<JSONObject> ownershipTransferList = (List<JSONObject>) JSONArray.toCollection(JSONArray.fromObject(ownershipTransfer), JSONObject.class);

        //删除附件再添加,发票是只填加不删除
        attachModuleDao.removeByCondition(" AND MODULE_ID = ? AND ATTACH_MODULE='18'", new String[]{mainId});
        attachModuleDao.removeByCondition(" AND MODULE_ID = ? AND ATTACH_MODULE='19'", new String[]{mainId});
        attachModuleDao.removeByCondition(" AND MODULE_ID = ? AND ATTACH_MODULE='20'", new String[]{mainId});
        if (certificateList != null && certificateList.size() > 0) {
            for (JSONObject attach : certificateList) {
                AttachmentEntity attachmentEntity = JSON.toJavaObject(attach, AttachmentEntity.class);
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attachmentEntity.getId());
                attachModuleEntity.setAttachModule(18);
                attachModuleEntity.setModuleId(mainId);
                attachModuleDao.add(attachModuleEntity);
            }
        }
        if (invoiceList != null && invoiceList.size() > 0) {
            for (JSONObject attach : invoiceList) {
                AttachmentEntity attachmentEntity = JSON.toJavaObject(attach, AttachmentEntity.class);
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attachmentEntity.getId());
                attachModuleEntity.setAttachModule(19);
                attachModuleEntity.setModuleId(mainId);
                attachModuleDao.add(attachModuleEntity);
            }
        }
        if (ownershipTransferList != null && ownershipTransferList.size() > 0) {
            for (JSONObject attach : ownershipTransferList) {
                AttachmentEntity attachmentEntity = JSON.toJavaObject(attach, AttachmentEntity.class);
                AttachModuleEntity attachModuleEntity = new AttachModuleEntity();
                attachModuleEntity.setAttachId(attachmentEntity.getId());
                attachModuleEntity.setAttachModule(20);
                attachModuleEntity.setModuleId(mainId);
                attachModuleDao.add(attachModuleEntity);
            }
        }
        return null;
    }

    @Override
    public JSONObject selectContractAccountList(String jsonData) {
        JSONObject json = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String auditFlag = json.getString("auditFlag");
        String haveDelivery = json.getString("haveDelivery");
        String customerKey = json.getString("customerKey");
        String haveSettle = json.getString("haveSettle");
        String key = json.getString("key");
        String userId = json.getString("userId");
        String companyId = json.getString("companyId");
        StringBuilder condition = new StringBuilder();
        String companyIds = "";
        if (!StringUtils.isBlank(auditFlag)) {
            condition.append("AND t_con_main.AUDIT_FLAG='" + auditFlag + "'");
        }
        if (!StringUtils.isBlank(haveDelivery)) {
            condition.append("AND t_con_main.HAVE_DELIVERY ='" + haveDelivery + "'");
        }
        if (!StringUtils.isBlank(key)) {
            condition.append(" AND t_con_main.BUYER LIKE '%" + key + "%' ");
        }
        String userIds = "";
        if (!StringUtils.isBlank(userId)) {
            userIds = checkDao.getChilderByUserId(userId, true);
            List<JSONObject> userMainList = userDao.getViewByUserId(" and id=? and main=1", new Object[]{userId});
            String manageFlag = userMainList.get(0).getString("manageFlag");
            String areaType = userMainList.get(0).getString("areaType");
            List<JSONObject> userList = userDao.getViewByUserId(" and id=?", new Object[]{userId});
            if (null != userList && userList.size() > 0) {
                for (int i = 0; i < userList.size(); i++) {
                    String selectCompanyId = userList.get(i).getString("companyId");
                    String ids = companyDao.getChilderCompanyByCompanyId(selectCompanyId).getString("companyIds");
                    //如果有下级
                    if (!StringUtils.isBlank(ids)) {
                        //如果有多个下级
                        if (ids.indexOf(",") >= 0) {
                            String[] idsSplit = ids.split(",");
                            for (String id : idsSplit) {
                                companyIds += "'" + id + "',";
                            }
                        } else {
                            //如果只有一个下级
                            companyIds += "'" + ids + "',";
                        }
                    }
                    companyIds += "'" + selectCompanyId + "',";
                }
                companyIds = companyIds.substring(0, companyIds.length() - 1);
            } else {
                companyIds = "''";
            }
            if (manageFlag.equals("1") || areaType.equals("2") || areaType.equals("3")) {
                userIds = "";
            } else {
                companyIds = "";
            }
        }
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (!StringUtils.isBlank(json.getString("pageSize"))) {
            pageSize = json.getInteger("pageSize");
        }
        if (!StringUtils.isBlank(json.getString("requestPage"))) {
            requestPage = json.getInteger("requestPage");
        }
        if (!StringUtils.isBlank(haveSettle)) {
            condition.append(" AND t_con_main.HAVE_SETTLE =" + haveSettle + " \n");
        }
        if (!StringUtils.isBlank(customerKey)) {
            condition.append(" AND (t_con_main.BUYER LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.SERIAL_NO LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.SELLER LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.CONTRACT_NO LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.BRAND_NAME LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.DEVICE_TYPE LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.MODEL_NAME LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.BUYER_TYPE LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.BUY_TYPE LIKE '%" + customerKey + "%' " +
                    "   or t_con_main.REGION_MANAGER_NAME LIKE '%" + customerKey + "%')\n");
        }

        if (!StringUtils.isBlank(companyIds)) {
            condition.append("AND (t_con_main.SELLER_COMPANY_ID IN (" + companyIds + ") AND t_con_main.AUDIT_FLAG='1')\n");
        }
        if (!StringUtils.isBlank(companyId) && !companyId.equals("201712161613432EAF27DBCCB7D0E6CA")) {
            condition.append(" AND t_con_main.SELLER_COMPANY_ID = '" + companyId + "'\n");
        }
        if (!StringUtils.isBlank(userIds)) {
            condition.append("AND (t_con_main.REGION_MANAGER_ID IN (" + userIds + ") AND t_con_main.AUDIT_FLAG='1')\n");
        }
        List<JSONObject> recordsList = contractMainDao.selectContractAccountList(condition.toString(), requestPage, pageSize);

        if (recordsList.size() > 0 && recordsList != null) {
            for (int i = 0; i < recordsList.size(); i++) {
                //添加到期日期到期金额
                JSONObject accountSubDate = new JSONObject();
                String type = "";
                accountSubDate = contractMainDao.getContractAccountSubDate(recordsList.get(i).getString("id"));
                if (accountSubDate != null) {
                    recordsList.get(i).put("accountSubDate", accountSubDate.getString("repayMent"));
                    recordsList.get(i).put("overDuePenalty", accountSubDate.getString("overDuePenalty"));
                    recordsList.get(i).put("remainingArrears", accountSubDate.getString("remainingArrears"));
                    type = accountSubDate.getString("type");
                    if (type.equals("2")||type.equals("4")) {
                        recordsList.get(i).put("accountSubMoney", accountSubDate.getString("contractRepayMentAmount"));
                    } else {
                        recordsList.get(i).put("accountSubMoney", accountSubDate.getString("total"));
                    }
                } else {
                    recordsList.get(i).put("accountSubDate", "");
                    recordsList.get(i).put("accountSubMoney", "");

                }
                //添加拼接款项
                List<JSONObject> accountType = new ArrayList<>();
                accountType = contractMainDao.getContractAccountType(recordsList.get(i).getString("id"));
                String kx = "";
                if (accountType != null && accountType.size() > 0) {
                    for (int j = 0; j < accountType.size(); j++) {
                        String kxType = "";
                        kxType = accountType.get(j).getString("type");
                        if (kxType.equals("3") || kxType.equals("1")) {
                            if (!kx.contains("首付款")) {
                                kx = kx + "首付款/";
                            }
                        } else if (kxType.equals("2") || kxType.equals("4")) {
                            if (!kx.contains("融资款")) {
                                kx = kx + "融资款/";
                            }
                        } else if (kxType.equals("0")) {
                            if (!kx.contains("分期款")) {
                                kx = kx + "分期款/";
                            }
                        }
                    }
                    if (!StringUtils.isBlank(kx)) {
                        recordsList.get(i).put("kx", kx.substring(0, kx.length() - 1));
                    } else {
                        recordsList.get(i).put("kx", "");
                    }
                } else {
                    recordsList.get(i).put("kx", "");

                }
            }
        }
        int recordCount = contractMainDao.selectContractAccountCount(condition.toString());
        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;
        //存放分页信息
        JSONObject sendData = new JSONObject();
        //存放list
        JSONObject result = new JSONObject();
        sendData.put("recordCount", recordCount);
        sendData.put("pageCount", pageCount);
        sendData.put("requestPage", 1);
        result.put("pager", sendData);
        // 子数组对象
        result.put("records", recordsList);
        return result;
    }

    @Override
    public JSONObject selectContractAccountListApp(String jsonData) {
        JSONObject json = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        String auditFlag = json.getString("auditFlag");
        String haveDelivery = json.getString("haveDelivery");
        String customerKey = json.getString("customerKey");
        String haveSettle = json.getString("haveSettle");
        String key = json.getString("key");
        String userId = json.getString("userId");
        String companyId = json.getString("companyId");
        StringBuilder condition = new StringBuilder();
        String companyIds = "";
        if (!StringUtils.isBlank(auditFlag)) {
            condition.append("AND t_con_main.AUDIT_FLAG='" + auditFlag + "'");
        }
        if (!StringUtils.isBlank(haveDelivery)) {
            condition.append("AND t_con_main.HAVE_DELIVERY ='" + haveDelivery + "'");
        }
        if (!StringUtils.isBlank(key)) {
            condition.append(" AND t_con_main.BUYER LIKE '%" + key + "%' ");
        }
        String userIds = "";
        if (!StringUtils.isBlank(userId)) {
            userIds = checkDao.getChilderByUserId(userId, true);
            List<JSONObject> userMainList = userDao.getViewByUserId(" and id=? and main=1", new Object[]{userId});
            String manageFlag = userMainList.get(0).getString("manageFlag");
            String areaType = userMainList.get(0).getString("areaType");
            List<JSONObject> userList = userDao.getViewByUserId(" and id=?", new Object[]{userId});
            if (null != userList && userList.size() > 0) {
                for (int i = 0; i < userList.size(); i++) {
                    String selectCompanyId = userList.get(i).getString("companyId");
                    String ids = companyDao.getChilderCompanyByCompanyId(selectCompanyId).getString("companyIds");
                    //如果有下级
                    if (!StringUtils.isBlank(ids)) {
                        //如果有多个下级
                        if (ids.indexOf(",") >= 0) {
                            String[] idsSplit = ids.split(",");
                            for (String id : idsSplit) {
                                companyIds += "'" + id + "',";
                            }
                        } else {
                            //如果只有一个下级
                            companyIds += "'" + ids + "',";
                        }
                    }
                    companyIds += "'" + selectCompanyId + "',";
                }
                companyIds = companyIds.substring(0, companyIds.length() - 1);
            } else {
                companyIds = "''";
            }
            if (manageFlag.equals("1") || areaType.equals("2") || areaType.equals("3")) {
                userIds = "";
            } else {
                companyIds = "";
            }
        }
        int requestPage = 1;
        int pageSize = Integer.MAX_VALUE;
        if (!StringUtils.isBlank(json.getString("pageSize"))) {
            pageSize = json.getInteger("pageSize");
        }
        if (!StringUtils.isBlank(json.getString("requestPage"))) {
            requestPage = json.getInteger("requestPage");
        }
        if (!StringUtils.isBlank(haveSettle)) {
            condition.append(" AND t_con_main.HAVE_SETTLE =" + haveSettle + " \n");
        }
        if (!StringUtils.isBlank(customerKey)) {
            condition.append(" AND (t_con_main.BUYER LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.SERIAL_NO LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.SELLER LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.CONTRACT_NO LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.BRAND_NAME LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.DEVICE_TYPE LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.MODEL_NAME LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.BUYER_TYPE LIKE '%" + customerKey + "%' " +
                    "   OR t_con_main.BUY_TYPE LIKE '%" + customerKey + "%' " +
                    "   or t_con_main.REGION_MANAGER_NAME LIKE '%" + customerKey + "%')\n");
        }

        if (!StringUtils.isBlank(companyIds)) {
            condition.append("AND (t_con_main.SELLER_COMPANY_ID IN (" + companyIds + ") AND t_con_main.AUDIT_FLAG='1')\n");
        }
        if (!StringUtils.isBlank(companyId) && !companyId.equals("201712161613432EAF27DBCCB7D0E6CA")) {
            condition.append(" AND t_con_main.SELLER_COMPANY_ID = '" + companyId + "'\n");
        }
        if (!StringUtils.isBlank(userIds)) {
            condition.append("AND (t_con_main.REGION_MANAGER_ID IN (" + userIds + ") AND t_con_main.AUDIT_FLAG='1')\n");
        }
        List<JSONObject> recordsList = contractMainDao.selectContractAccountListApp(condition.toString(), requestPage, pageSize);
        List<JSONObject> list=new ArrayList<>();
        for (int i = 0; i < recordsList.size(); i++) {
            if (StringUtils.isBlank(recordsList.get(i).getString("repaymentDate"))){
                list.add(recordsList.get(i));
            }else{
                if (recordsList.get(i).getInteger("haveDsdf") == 0 && (recordsList.get(i).getInteger("type") != 2 && recordsList.get(i).getInteger("type") != 4)) {
                    list.add(recordsList.get(i));
                }
                if (recordsList.get(i).getInteger("haveDsdf") == 1 && (recordsList.get(i).getInteger("type") != 10 && recordsList.get(i).getInteger("type") != 12)) {
                    list.add(recordsList.get(i));
                }
            }
        }
        List<JSONObject> recordsList1 = contractMainDao.selectContractAccountListApp(condition.toString(), 1, Integer.MAX_VALUE);
        List<JSONObject> list1=new ArrayList<>();
        for (int i = 0; i < recordsList1.size(); i++) {
            if (StringUtils.isBlank(recordsList1.get(i).getString("repaymentDate"))){
                list1.add(recordsList1.get(i));
            }else{
                if (recordsList1.get(i).getInteger("haveDsdf") == 0 && (recordsList1.get(i).getInteger("type") != 2 && recordsList1.get(i).getInteger("type") != 4)) {
                    list1.add(recordsList1.get(i));
                }
                if (recordsList1.get(i).getInteger("haveDsdf") == 1 && (recordsList1.get(i).getInteger("type") != 10 && recordsList1.get(i).getInteger("type") != 12)) {
                    list1.add(recordsList1.get(i));
                }
            }
        }
        int recordCount = list1.size();
        //如果整除表示正好分N页，如果不能整除在N页的基础上+1页
        int pageCount = recordCount % pageSize == 0 ? recordCount / pageSize : (recordCount / pageSize) + 1;
        //存放分页信息
        JSONObject sendData = new JSONObject();
        //存放list
        JSONObject result = new JSONObject();
        sendData.put("recordCount", recordCount);
        sendData.put("pageCount", pageCount);
        sendData.put("requestPage", 1);
        result.put("pager", sendData);
        // 子数组对象
        result.put("records", list);
        return result;
    }

    @Override
    public List<JSONObject> getRepaymentDate() {
        return repaymentDao.getRepaymentDate();
    }

    @Override
    public List<JSONObject> exportContractAccountList() {
        return contractMainDao.selectExportAccountList();
    }

    @Override
    public Boolean senderExpire() {
        contractMainDao.updateExpire();
        List<JSONObject> contractList = contractMainDao.senderExpire();
        if (contractList != null && contractList.size() > 0) {
            for (int i = 0; i < contractList.size(); i++) {
                JSONObject contract = contractList.get(i);
                ContractMainEntity entity = (ContractMainEntity) contractMainDao.getIBaseEntityById(contract.getString("mainId"));
                if (entity.getHaveOverdue() != 1) {
                    entity.setHaveOverdue(2);
                    entity.setHaveOverdueNo(contract.getInteger("repaymentDate"));
                    contractMainDao.update(entity);
                }
            }
            return true;
        }
        return false;
    }

    @Override
    public Boolean senderMessage(String mainId) {
        String months = DateUtils.nowMouthByString(repaymentDao.getCurrentTime());
        JSONObject sender = new JSONObject();
        StringBuilder sb = new StringBuilder();
        sender = repaymentDao.getRepaymentSender(mainId);
        if (sender == null) {
            sender = repaymentDao.getRepaymentSender(mainId, months);
        }
        String customerName = sender.getString("customerName");
        String customerTel = sender.getString("customerTel");
        String brandName = sender.getString("brandName");
        String modelName = sender.getString("modelName");
        String buyerTaxNo = sender.getString("buyerTaxNo");
        String deviceName = sender.getString("deviceName");
        String repaymentDate = sender.getString("repaymentDate");
        String serialNo = sender.getString("serialNo");
        String regionManagerId = sender.getString("regionManagerId");
        String bigRegionManagerId = sender.getString("bigRegionManagerId");
        String regionalSupportId = sender.getString("regionalSupportId");
        String createUserId = sender.getString("createUserId");
        String creditManagerId = sender.getString("creditManagerId");
        String dataOfficerId = sender.getString("dataOfficerId");
        String takeOverManagerId = sender.getString("takeOverManagerId");
        if (StringUtils.isNotEmpty(regionManagerId)) {
            sb.append("|");
            sb.append(regionManagerId);
        }
        if (StringUtils.isNotEmpty(bigRegionManagerId)) {
            sb.append("|");
            sb.append(bigRegionManagerId);
        }
        if (StringUtils.isNotEmpty(regionalSupportId)) {
            sb.append("|");
            sb.append(regionalSupportId);
        }
        if (StringUtils.isNotEmpty(createUserId)) {
            sb.append("|");
            sb.append(createUserId);
        }
        if (StringUtils.isNotEmpty(creditManagerId)) {
            sb.append("|");
            sb.append(creditManagerId);
        }
        if (StringUtils.isNotEmpty(dataOfficerId)) {
            sb.append("|");
            sb.append(dataOfficerId);
        }
        if (StringUtils.isNotEmpty(takeOverManagerId)) {
            sb.append("|");
            sb.append(takeOverManagerId);
        }
        sb.append("|");
        sb.append("201712182044422D8254F02E0151637E");
        if (sb.length() > 0) {
            sb.deleteCharAt(0);
        }
        String httpHtml = "http://oa.yingfeng365.com/page/accountMessageNew.html?id=" + mainId + "";
        String url = "http://suo.im/api.php?format=json&url=";
        JSONObject dlRequest = HttpUtil.request(url + httpHtml,
                "GET", null);
        String ysHtml = dlRequest.getString("url");
        String sendName = "";
        if (customerName.length() > 6) {
            sendName = "";
        } else {
            sendName = matchesOdd(buyerTaxNo);
        }
        JSONObject msgObject = new JSONObject();
        msgObject.put("userIds", sb);
        msgObject.put("content", String.format(SENDER_INNER_REMIND, customerName, sendName, brandName,
                deviceName, modelName,
                serialNo, repaymentDate, ysHtml));
        tokenDao.sendTextMsg(msgObject.toJSONString());
        return true;
    }

    @Override
    public JSONObject getRepaymentSender(String jsonData) {
        JSONObject jsonParams = FastJsonConvert.convertJSONToObject(jsonData, JSONObject.class);
        JSONObject sender = new JSONObject();
        List<JSONObject> repaymentList = new ArrayList<>();
        String months = DateUtils.nowMouthByString(repaymentDao.getCurrentTime());
        String maindId = jsonParams.getString("mainId");
        sender = repaymentDao.getRepaymentSender(maindId);
        if (sender == null) {
            sender = repaymentDao.getRepaymentSender(maindId, months);
        }
        String customerName = sender.getString("customerName");
        String customerTel = sender.getString("customerTel");
        String buyerTaxNo = sender.getString("buyerTaxNo");
        String haveDsdf = sender.getString("haveDsdf");
        String brandName = sender.getString("brandName");
        String modelName = sender.getString("modelName");
        String deviceName = sender.getString("deviceName");
        String repaymentDate = sender.getString("repaymentDate");
        String serialNo = sender.getString("serialNo");
        String buyType = sender.getString("buyType");
        String comName = "";
        String signName = "";
        String sendName = "";
        if (customerName.length() > 6) {
            sendName = "";
        } else {
            sendName = matchesOdd(buyerTaxNo);
        }
        switch (sender.getString("companyName")) {
            case "黑龙江灜源":
                comName = SendConstant.SENDER_HLJ;
                signName = SendConstant.COMPANY_HLJ;
                break;
            case "吉林清源":
                comName = SendConstant.SENDER_JL;
                signName = SendConstant.COMPANY_JL;
                break;
            case "辽宁灜湖":
                comName = SendConstant.SENDER_LN;
                signName = SendConstant.COMPANY_LN;
                break;
            case "江苏滚滚向前":
                comName = SendConstant.SENDER_GGXQ;
                signName = SendConstant.COMPANY_GGXQ;
                break;
            case "安徽灜湖":
                comName = SendConstant.SENDER_AH;
                signName = SendConstant.COMPANY_AN;
                break;
            case "河北灜源":
                comName = SendConstant.SENDER_HB;
                signName = SendConstant.COMPANY_HB;
                break;
            case "甘肃&宁夏":
                comName = SendConstant.SENDER_GS;
                signName = SendConstant.COMPANY_GS;
                break;
            case "湖南清源":
                comName = SendConstant.SENDER_HN;
                signName = SendConstant.COMPANY_HN;
                break;
            default:
                break;
        }
  /*      String httpHtml = "http://oa.yingfeng365.com/page/accountMessageNew.html?id=" + maindId + "";
        String url = "http://dwz.cn/admin/create";
        JSONObject paramJsonObject=new JSONObject();
        paramJsonObject.put("URL", httpHtml);
        JSONObject dlRequest = HttpUtil.request(url,
                "POST",paramJsonObject.toJSONString() );
        String ysHtml = dlRequest.getString("ShortUrl");*/
        String httpHtml = "http://oa.yingfeng365.com/page/accountMessageNew.html?id=" + maindId + "";
        String url = "http://suo.im/api.php?format=json&url=";
        JSONObject dlRequest = HttpUtil.request(url + httpHtml,
                "GET", null);
        String ysHtml = dlRequest.getString("url");
        String content = String.format(SENDER_CUS_REMIND,
                customerName, sendName, brandName,
                deviceName, modelName,
                serialNo, repaymentDate, ysHtml);
        JSONObject repaymentMoney = repaymentDao.getRepaymentAmount(repaymentDate, maindId);
        if(buyType.equals("内部分期")){
            repaymentList  = (List<JSONObject>) (Object) availableDao.getJSONListByCondition(" AND MAIN_ID=?  ORDER BY AVAILABLE_DATE DESC", new Object[]{maindId});

        }else{
            if (haveDsdf.equalsIgnoreCase("1")) {
                repaymentList = repaymentDao.getRepaymentHistory(maindId);
            } else {
                repaymentList = repaymentDao.getFinancingHistory(maindId);
            }
        }

        JSONObject result = new JSONObject();
        result.put("customerTel", customerTel);
        result.put("content", content);
        result.put("signName", signName);
        result.put("comName", comName);
        result.put("sender", sender);
        result.put("repaymentMoney", repaymentMoney);
        result.put("repaymentList", repaymentList);
        return result;
    }

    //公共保存方法
    private void getRepaymentSave(List<RepaymentEntity> repaymentaSFEntityList, String mainId, String createUserId, String createUserName) {
        for (int i = 0; i < repaymentaSFEntityList.size(); i++) {
            RepaymentEntity repaymentEntity = repaymentaSFEntityList.get(i);
            if ("0".equals(repaymentEntity.getId()) || StringUtils.isBlank(repaymentEntity.getId())) {
                //模块0-内部分期/1-垫款/2-融资分期/3-首付款信息
                repaymentEntity.setType(3);
                repaymentEntity.setMainId(mainId);
                repaymentEntity.setSortNo(i);
                repaymentEntity.setCreateUserName(createUserName);
                repaymentEntity.setCreateUserId(createUserId);
                repaymentEntity.setCreateDate(DateUtils.nowSFByString(repaymentDao.getCurrentTime()));
                repaymentDao.add(repaymentEntity);
            } else {
                RepaymentEntity entity = (RepaymentEntity) repaymentDao.getIBaseEntityById(repaymentEntity.getId());
                entity.setMainId(mainId);
                entity.setTotal(repaymentEntity.getTotal());
                entity.setRepaymentDate(repaymentEntity.getRepaymentDate());
                entity.setActualRepaymentDate(repaymentEntity.getActualRepaymentDate());
                entity.setRepaymentAmount(repaymentEntity.getRepaymentAmount());
                entity.setOverduePenalty(repaymentEntity.getOverduePenalty());
                entity.setRemainingArrears(repaymentEntity.getRemainingArrears());
                entity.setRemark(repaymentEntity.getRemark());
                entity.setRepaymentAttachName(repaymentEntity.getRepaymentAttachName());
                entity.setRepaymentAttachUrl(repaymentEntity.getRepaymentAttachUrl());
                entity.setCreateUserName(repaymentEntity.getCreateUserName());
                entity.setCreateUserId(repaymentEntity.getCreateUserId());
                repaymentDao.update(entity);
            }
            //保存&修改子list
            if (repaymentEntity.getRepaymentParentList() != null && repaymentEntity.getRepaymentParentList().size() > 0) {
                for (int j = 0; j < repaymentEntity.getRepaymentParentList().size(); j++) {
                    RepaymentEntity entityParent = (RepaymentEntity) repaymentDao.getIBaseEntityById(
                            repaymentEntity.getRepaymentParentList().get(j).getId());
                    if (entityParent == null) {
                        repaymentEntity.getRepaymentParentList().get(j).setMainId(mainId);
                        repaymentEntity.getRepaymentParentList().get(j).setType(3);
                        repaymentEntity.getRepaymentParentList().get(j).setSortNo(j);
                        repaymentEntity.getRepaymentParentList().get(j).setParentId(repaymentEntity.getId());
                        repaymentEntity.getRepaymentParentList().get(j).setCreateUserName(createUserName);
                        repaymentEntity.getRepaymentParentList().get(j).setCreateUserId(createUserId);
                        repaymentEntity.getRepaymentParentList().get(j).setCreateDate(DateUtils.nowSFByString(repaymentDao.getCurrentTime()));
                        repaymentDao.add(repaymentEntity.getRepaymentParentList().get(j));
                    } else {
                        entityParent.setMainId(mainId);
                        entityParent.setActualRepaymentDate(repaymentEntity.getRepaymentParentList().get(j).getActualRepaymentDate());
                        entityParent.setRepaymentAmount(repaymentEntity.getRepaymentParentList().get(j).getRepaymentAmount());
                        entityParent.setOverduePenalty(repaymentEntity.getRepaymentParentList().get(j).getOverduePenalty());
                        entityParent.setRemainingArrears(repaymentEntity.getRepaymentParentList().get(j).getRemainingArrears());
                        entityParent.setRemark(repaymentEntity.getRepaymentParentList().get(j).getRemark());
                        entityParent.setRepaymentAttachName(repaymentEntity.getRepaymentParentList().get(j).getRepaymentAttachName());
                        entityParent.setRepaymentAttachUrl(repaymentEntity.getRepaymentParentList().get(j).getRepaymentAttachUrl());
                        entityParent.setCreateUserName(repaymentEntity.getRepaymentParentList().get(j).getCreateUserName());
                        entityParent.setCreateUserId(repaymentEntity.getRepaymentParentList().get(j).getCreateUserId());
                        repaymentDao.update(entityParent);
                    }
                }
            }
        }
    }

    //公共保存罚息欠款方法
    private void getRepaymentSaveOvRe(List<RepaymentEntity> repaymentEntities) {
        for (int i = 0; i < repaymentEntities.size(); i++) {
            RepaymentEntity repaymentEntity = repaymentEntities.get(i);
            RepaymentEntity entity = (RepaymentEntity) repaymentDao.getIBaseEntityById(repaymentEntity.getId());
            if (entity != null) {
                entity.setOverduePenalty(repaymentEntity.getOverduePenalty());
                entity.setRemainingArrears(repaymentEntity.getRemainingArrears());
                repaymentDao.update(entity);
            }

            //保存&修改子list
            if (repaymentEntity.getRepaymentParentList() != null && repaymentEntity.getRepaymentParentList().size() > 0) {
                for (int j = 0; j < repaymentEntity.getRepaymentParentList().size(); j++) {
                    RepaymentEntity entityParent = (RepaymentEntity) repaymentDao.getIBaseEntityById(
                            repaymentEntity.getRepaymentParentList().get(j).getId());
                    if (entityParent != null) {
                        entityParent.setOverduePenalty(repaymentEntity.getRepaymentParentList().get(j).getOverduePenalty());
                        entityParent.setRemainingArrears(repaymentEntity.getRepaymentParentList().get(j).getRemainingArrears());
                        repaymentDao.update(entityParent);
                    }
                }
            }
        }
    }

    //公共保存罚息欠款方法(融资合同)
    private void getRepaymentSaveOvReFn(List<FinancingEntity> repaymentEntities) {
        for (int i = 0; i < repaymentEntities.size(); i++) {
            FinancingEntity repaymentEntity = repaymentEntities.get(i);
            FinancingEntity entity = (FinancingEntity) financingDao.getIBaseEntityById(repaymentEntity.getId());
            if (entity != null) {
                entity.setJroverduePenalty(repaymentEntity.getJroverduePenalty());
                entity.setRemainingArrears(repaymentEntity.getRemainingArrears());
                financingDao.update(entity);
            }
            //保存&修改子list
            if (repaymentEntity.getRepaymentParentList() != null && repaymentEntity.getRepaymentParentList().size() > 0) {
                for (int j = 0; j < repaymentEntity.getRepaymentParentList().size(); j++) {
                    FinancingEntity entityParent = (FinancingEntity) financingDao.getIBaseEntityById(
                            repaymentEntity.getRepaymentParentList().get(j).getId());
                    if (entityParent != null) {
                        entityParent.setJroverduePenalty(repaymentEntity.getRepaymentParentList().get(j).getJroverduePenalty());
                        entityParent.setRemainingArrears(repaymentEntity.getRepaymentParentList().get(j).getRemainingArrears());
                        financingDao.update(entityParent);
                    }

                }
            }
        }
    }

    //判断是否逾期
    private void getOverDue(String mainId, BigDecimal yqSum, String dateTime, BigDecimal total, String repaymentDate, String nowDate, BigDecimal overduePenalty,BigDecimal remainingArrears) {
        ContractMainEntity mainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(mainId);
        if (StringUtils.isBlank(dateTime)||remainingArrears.compareTo(new BigDecimal(0.00)) > 0) {
            dateTime = nowDate;
        }
        if ((total.compareTo(yqSum) > 0 &&
                dateTime.compareTo(repaymentDate) >= 0) || overduePenalty.compareTo(new BigDecimal(0.00)) > 0|| remainingArrears.compareTo(new BigDecimal(0.00)) > 0) {
            if (mainEntity.getHaveOverdue() == 0) {
                Integer haveOverdueNo = DateUtils.getDaySub(repaymentDate, dateTime);
                if (haveOverdueNo != -6 && haveOverdueNo > 0) {
                    mainEntity.setHaveOverdue(1);
                    flag = false;
                    mainEntity.setHaveOverdueNo(haveOverdueNo + 1);
                    contractMainDao.update(mainEntity);
                } else {
                    if (repaymentDate.compareTo(nowDate) <= 0) {
                        Integer overdueNo = DateUtils.getDaySub(nowDate, repaymentDate);
                        flag = false;
                        mainEntity.setHaveOverdue(1);
                        mainEntity.setHaveOverdueNo(overdueNo + 1);
                        contractMainDao.update(mainEntity);
                    }
                }
            }
        } else {
            if (mainEntity.getHaveOverdue() != 2) {
                if (flag) {
                    mainEntity.setHaveOverdue(0);
                    mainEntity.setHaveOverdueNo(-6);
                    contractMainDao.update(mainEntity);

                }
            }
        }
    }

    //私有的查询和导出公共的方法
    private JSONObject getContractByCondition(String mainId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        ContractEntity entity = new ContractEntity();
        ContractMainEntity contractMainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(mainId);
        if (StringUtils.isBlank(contractMainEntity.getCustomerCredit())) {
            if (contractMainEntity.getHaveOverdue() == 1) {
                Integer overdueNo = contractMainEntity.getHaveOverdueNo();
                if (overdueNo <= 30) {
                    contractMainEntity.setCustomerCredit("1-1类：逾期1-30天");
                } else if (31 < overdueNo && overdueNo <= 60) {
                    contractMainEntity.setCustomerCredit("1-2类：逾期31-60天");
                } else {
                    contractMainEntity.setCustomerCredit("1-3类：逾期60天以上");
                }
            } else {
                contractMainEntity.setCustomerCredit("0类：无逾期");
            }
        }
        //查看购买方式是否为内部分期
        if (contractMainEntity.getBuyType().equals("内部分期")) {
            List<RepaymentEntity> repaymentFQList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND MAIN_ID=? AND PARENT_ID=0 AND TYPE=0  order by SORT_NO", new Object[]{mainId});//分期列表
            if (repaymentFQList != null && repaymentFQList.size() > 0) {
                for (int i = 0; i < repaymentFQList.size(); i++) {
                    RepaymentEntity repaymentEntity = repaymentFQList.get(i);
                    List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND PARENT_ID=? AND TYPE=0 order by SORT_NO", new Object[]{repaymentEntity.getId()});
                    repaymentEntity.setRepaymentParentList(repaymentParentList);
                    calRemainingArrears(repaymentEntity, repaymentParentList, "1");
                }
            }
            entity.setRepaymentFQList(repaymentFQList);
        } else {
            RepaymentEntity repaymentFQEntity = new RepaymentEntity();//内部分期
            List<RepaymentEntity> repaymentaFQEntityList = new ArrayList<RepaymentEntity>();
            repaymentaFQEntityList.add(repaymentFQEntity);
            entity.setRepaymentFQList(repaymentaFQEntityList);
        }
        //查看购买方式是否为内部分期并且有首付款分期
        if (contractMainEntity.getBuyType().equals("内部分期") && contractMainEntity.getHaveFQFirst() == 1) {
            List<RepaymentEntity> repaymentFQFirstList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND MAIN_ID=? AND PARENT_ID=0 AND TYPE=5  order by SORT_NO", new Object[]{mainId});//分期首付款分期
            if (repaymentFQFirstList != null && repaymentFQFirstList.size() > 0) {
                for (int i = 0; i < repaymentFQFirstList.size(); i++) {
                    RepaymentEntity repaymentEntity = repaymentFQFirstList.get(i);
                    List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND PARENT_ID=? AND TYPE=5 order by SORT_NO", new Object[]{repaymentEntity.getId()});
                    repaymentEntity.setRepaymentParentList(repaymentParentList);
                }
            }
            entity.setRepaymentFQFirstList(repaymentFQFirstList);

        } else {
            RepaymentEntity repaymentFQEntity = new RepaymentEntity();//内部分期
            List<RepaymentEntity> repaymentFQFirstList = new ArrayList<RepaymentEntity>();
            repaymentFQFirstList.add(repaymentFQEntity);
            entity.setRepaymentFQFirstList(repaymentFQFirstList);
        }
        //查看购买方式是否为融资租赁
        if (contractMainEntity.getBuyType().equals("融资租赁")) {
            List<RepaymentEntity> repaymentRZList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND MAIN_ID=? AND PARENT_ID=0 AND TYPE=2  order by SORT_NO", new Object[]{mainId});//分期列表
            if (null == repaymentRZList || repaymentRZList.size() == 0) {
                RepaymentEntity repaymentRZEntity = new RepaymentEntity();
                repaymentRZList.add(repaymentRZEntity);
            }
            if (repaymentRZList != null && repaymentRZList.size() > 0) {
                for (int i = 0; i < repaymentRZList.size(); i++) {
                    RepaymentEntity repaymentEntity = repaymentRZList.get(i);
                    List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND PARENT_ID=? AND TYPE=2 order by SORT_NO", new Object[]{repaymentEntity.getId()});
                    repaymentEntity.setRepaymentParentList(repaymentParentList);
                    if (contractMainEntity.getHaveDsdf() != 0) {
                        calRemainingArrears(repaymentEntity, repaymentParentList, "0");
                    }
                }
            }
            entity.setRepaymentRZList(repaymentRZList);
            //融资分期跟踪
            List<FinancingEntity> financingRZList = (List<FinancingEntity>) (Object) financingDao.getIBaseEntityByCondition(" AND MAIN_ID=? AND PARENT_ID='0' AND TYPE=2 ORDER BY SORT_NO ", new Object[]{mainId});
            if (null == financingRZList || financingRZList.size() == 0) {
                FinancingEntity financingEntity = new FinancingEntity();
                financingRZList.add(financingEntity);
            }
            for (int i = 0; i < financingRZList.size(); i++) {
                FinancingEntity financingEntity = financingRZList.get(i);
                List<FinancingEntity> repaymentParentList = (List<FinancingEntity>) (Object) financingDao.getIBaseEntityByCondition(" AND PARENT_ID=? AND TYPE=2  order by SORT_NO", new Object[]{financingEntity.getId()});
                financingEntity.setRepaymentParentList(repaymentParentList);
                if (StringUtils.isNotEmpty(financingEntity.getFinancingDate())) {
                    calRemainingArrears(financingEntity, repaymentParentList);
                }
            }
            entity.setFinancingRZList(financingRZList);

        } else {
            RepaymentEntity repaymentRZEntity = new RepaymentEntity();
            List<RepaymentEntity> repaymentaRZEntityList = new ArrayList<RepaymentEntity>();
            repaymentaRZEntityList.add(repaymentRZEntity);
            entity.setRepaymentRZList(repaymentaRZEntityList);
            //融资分期款跟踪
            FinancingEntity financingEntity = new FinancingEntity();
            List<FinancingEntity> financingRZList = new ArrayList<FinancingEntity>();
            financingRZList.add(financingEntity);
            entity.setFinancingRZList(financingRZList);

        }
        //查看购买方式是否为融资租赁打包
        if (contractMainEntity.getBuyType().equals("融资租赁打包")) {
            List<RepaymentEntity> repaymentRZDBList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND MAIN_ID=? AND PARENT_ID=0 AND TYPE=4  order by SORT_NO", new Object[]{mainId});//分期列表
            if (null == repaymentRZDBList || repaymentRZDBList.size() == 0) {
                RepaymentEntity repaymentRZDBEntity = new RepaymentEntity();
                repaymentRZDBList.add(repaymentRZDBEntity);
            }
            if (repaymentRZDBList != null && repaymentRZDBList.size() > 0) {
                for (int i = 0; i < repaymentRZDBList.size(); i++) {
                    RepaymentEntity repaymentEntity = repaymentRZDBList.get(i);
                    List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND PARENT_ID=? AND TYPE=4 order by SORT_NO", new Object[]{repaymentEntity.getId()});
                    repaymentEntity.setRepaymentParentList(repaymentParentList);
                    if (contractMainEntity.getHaveDsdf() != 0) {
                        calRemainingArrears(repaymentEntity, repaymentParentList, "0");
                    }
                }
            }
            entity.setRepaymentRZDBList(repaymentRZDBList);
            //融资分期跟踪
            List<FinancingEntity> financingRZDBList = (List<FinancingEntity>) (Object) financingDao.getIBaseEntityByCondition(" AND MAIN_ID=? AND PARENT_ID='0' AND TYPE=4  ORDER BY SORT_NO ", new Object[]{mainId});
            if (null == financingRZDBList || financingRZDBList.size() == 0) {
                FinancingEntity financingEntity = new FinancingEntity();
                financingRZDBList.add(financingEntity);
            }
            for (int i = 0; i < financingRZDBList.size(); i++) {
                FinancingEntity financingEntity = financingRZDBList.get(i);
                List<FinancingEntity> repaymentParentList = (List<FinancingEntity>) (Object) financingDao.getIBaseEntityByCondition(" AND PARENT_ID=? AND TYPE=4  order by SORT_NO", new Object[]{financingEntity.getId()});
                financingEntity.setRepaymentParentList(repaymentParentList);
                if (StringUtils.isNotEmpty(financingEntity.getFinancingDate())) {
                    calRemainingArrears(financingEntity, repaymentParentList);
                }
            }
            entity.setFinancingRZDBList(financingRZDBList);

        } else {
            RepaymentEntity repaymentRZDBEntity = new RepaymentEntity();
            List<RepaymentEntity> repaymentRZDBList = new ArrayList<RepaymentEntity>();
            repaymentRZDBList.add(repaymentRZDBEntity);
            entity.setRepaymentRZDBList(repaymentRZDBList);
            //融资分期款跟踪
            FinancingEntity financingEntity = new FinancingEntity();
            List<FinancingEntity> financingRZDBList = new ArrayList<FinancingEntity>();
            financingRZDBList.add(financingEntity);
            entity.setFinancingRZDBList(financingRZDBList);
        }
        //查看是否有垫款
        if (contractMainEntity.getHaveRepayment() == 1) {
            List<RepaymentEntity> repaymentDKList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND MAIN_ID=? AND PARENT_ID=0  AND TYPE=1  order by SORT_NO", new Object[]{mainId});//垫款列表
            if (repaymentDKList != null && repaymentDKList.size() > 0) {
                for (int i = 0; i < repaymentDKList.size(); i++) {
                    RepaymentEntity repaymentEntity = repaymentDKList.get(i);
                    List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND PARENT_ID=? AND TYPE=1 order by SORT_NO", new Object[]{repaymentEntity.getId()});
                    repaymentEntity.setRepaymentParentList(repaymentParentList);
                    calRemainingArrears(repaymentEntity, repaymentParentList, "1");
                }
            }
            entity.setRepaymentDKList(repaymentDKList);
        }
        //添加首付款信息
        List<RepaymentEntity> repaymentSFList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND MAIN_ID=? AND PARENT_ID=0 AND TYPE=3 order by SORT_NO", new Object[]{mainId});//首付款信息
        //添加首付款信息分期中的分期
        if (repaymentSFList != null && repaymentSFList.size() > 0) {
            for (int i = 0; i < repaymentSFList.size(); i++) {
                RepaymentEntity repaymentEntity = repaymentSFList.get(i);
                List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition(" AND PARENT_ID=? AND TYPE=3 order by SORT_NO", new Object[]{repaymentEntity.getId()});
                repaymentEntity.setRepaymentParentList(repaymentParentList);
                calRemainingArrears(repaymentEntity, repaymentParentList, "1");
            }
        }
        entity.setRepaymentSFList(repaymentSFList);
        //添加催款记录
        List<CollectionEntity> collectionEntityList = (List<CollectionEntity>) (Object) collectionDao.getIBaseEntityByCondition(" AND MAIN_ID=? order by SORT_NO", new Object[]{mainId});
        if (collectionEntityList != null && collectionEntityList.size() > 0) {
            entity.setCollectionList(collectionEntityList);
        } else {
            CollectionEntity collectionEntity = new CollectionEntity();
            List<CollectionEntity> collectionEntityList1 = new ArrayList<CollectionEntity>();
            collectionEntityList1.add(collectionEntity);
            entity.setCollectionList(collectionEntityList1);
        }
        //添加区域经理
        List<ContractHistoryEntity> regionManagerList = (List<ContractHistoryEntity>) (Object) contractHistoryDao.getIBaseEntityByCondition(" AND MAIN_ID=? AND TYPE=0 ORDER BY SORT_NO", new Object[]{mainId});
        if (regionManagerList != null && regionManagerList.size() > 0) {
            entity.setRegionManagerList(regionManagerList);
        } else {
            ContractHistoryEntity historyEntity = new ContractHistoryEntity();
            List<ContractHistoryEntity> contractHistoryEntityList = new ArrayList<ContractHistoryEntity>();
            contractHistoryEntityList.add(historyEntity);
            entity.setRegionManagerList(contractHistoryEntityList);
        }
        //添加大区经理
        List<ContractHistoryEntity> bigRegionManagerList = (List<ContractHistoryEntity>) (Object) contractHistoryDao.getIBaseEntityByCondition(" AND MAIN_ID=? AND TYPE=1 ORDER BY SORT_NO", new Object[]{mainId});
        if (bigRegionManagerList != null && bigRegionManagerList.size() > 0) {
            entity.setBigRegionManagerList(bigRegionManagerList);
        } else {
            ContractHistoryEntity historyEntity = new ContractHistoryEntity();
            List<ContractHistoryEntity> contractHistoryEntityList = new ArrayList<ContractHistoryEntity>();
            contractHistoryEntityList.add(historyEntity);
            entity.setBigRegionManagerList(contractHistoryEntityList);
        }
        //添加区域支持
        List<ContractHistoryEntity> regionSupportList = (List<ContractHistoryEntity>) (Object) contractHistoryDao.getIBaseEntityByCondition(" AND MAIN_ID=? AND TYPE=2 ORDER BY SORT_NO", new Object[]{mainId});
        if (bigRegionManagerList != null && bigRegionManagerList.size() > 0) {
            entity.setRegionSupportList(regionSupportList);
        } else {
            ContractHistoryEntity historyEntity = new ContractHistoryEntity();
            List<ContractHistoryEntity> contractHistoryEntityList = new ArrayList<ContractHistoryEntity>();
            contractHistoryEntityList.add(historyEntity);
            entity.setRegionSupportList(contractHistoryEntityList);
        }
        //添加债权经理
        List<ContractHistoryEntity> creditorManagerList = (List<ContractHistoryEntity>) (Object) contractHistoryDao.getIBaseEntityByCondition(" AND MAIN_ID=? AND TYPE=3 ORDER BY SORT_NO", new Object[]{mainId});
        if (creditorManagerList != null && creditorManagerList.size() > 0) {
            entity.setCreditorManagerList(creditorManagerList);
        } else {
            ContractHistoryEntity historyEntity = new ContractHistoryEntity();
            List<ContractHistoryEntity> contractHistoryEntityList = new ArrayList<ContractHistoryEntity>();
            contractHistoryEntityList.add(historyEntity);
            entity.setCreditorManagerList(contractHistoryEntityList);
        }
        //添加应收专员
        List<ContractHistoryEntity> dataManagerList = (List<ContractHistoryEntity>) (Object) contractHistoryDao.getIBaseEntityByCondition(" AND MAIN_ID=? AND TYPE=4 ORDER BY SORT_NO", new Object[]{mainId});
        if (dataManagerList != null && dataManagerList.size() > 0) {
            entity.setDataManagerList(dataManagerList);
        } else {
            ContractHistoryEntity historyEntity = new ContractHistoryEntity();
            List<ContractHistoryEntity> contractHistoryEntityList = new ArrayList<ContractHistoryEntity>();
            contractHistoryEntityList.add(historyEntity);
            entity.setDataManagerList(contractHistoryEntityList);
        }
        //添加收款记录
        List<AvailableEntity> availableList = (List<AvailableEntity>) (Object) availableDao.getIBaseEntityByCondition(" AND MAIN_ID=?  ORDER BY AVAILABLE_DATE", new Object[]{mainId});
        if (availableList != null && availableList.size() > 0) {
            entity.setAvailableList(availableList);
        } else {
            AvailableEntity availableEntity = new AvailableEntity();
            List<AvailableEntity> availableEntities = new ArrayList<AvailableEntity>();
            availableEntities.add(availableEntity);
            entity.setAvailableList(availableEntities);
        }
        //添加合同主表信息getRepaymentSender
        entity.setMain(contractMainEntity);
        ContractSalesEntity contractSalesEntity = (ContractSalesEntity) contractSalesDao.getIBaseEntityByCondition("AND MAIN_ID=? AND LOG_FLAG=0 ", new Object[]{mainId}).get(0);
        entity.setSales(contractSalesEntity);
        List<ReplacementEntity> replacementEntityList = (List<ReplacementEntity>) (Object) replacementDao.getIBaseEntityByCondition(" and main_id=?", new String[]{mainId});
        //查看是否是置换
        if (contractMainEntity.getHaveReplacement() == 1) {
            List<IBaseEntity> replacement = replacementDao.getIBaseEntityByCondition("AND MAIN_ID=? ", new Object[]{mainId});
            if (null != replacement && replacement.size() > 0) {
                ReplacementEntity replacementEntity = (ReplacementEntity) replacement.get(0);
                List<DeviceDisplaceEntity> zzj = new ArrayList<DeviceDisplaceEntity>();//旧挖掘机
                List<DeviceDisplaceEntity> wjj = new ArrayList<DeviceDisplaceEntity>();//旧装载机
                List<DeviceDisplaceEntity> fangWu = new ArrayList<DeviceDisplaceEntity>();//旧房屋置换
                List<DeviceDisplaceEntity> qiChe = new ArrayList<DeviceDisplaceEntity>();//旧汽车置换
                List<DeviceDisplaceEntity> other = new ArrayList<DeviceDisplaceEntity>();//其他置换信息
                String replacementsName = replacementEntity.getReplacementsName();
                DeviceDisplaceEntity deviceDisplaceEntity = new DeviceDisplaceEntity();
                if (!replacementsName.contains("zzj")) {
                    zzj.add(deviceDisplaceEntity);
                }
                if (!replacementsName.contains("wjj")) {
                    wjj.add(deviceDisplaceEntity);
                }
                if (!replacementsName.contains("fangWu")) {
                    fangWu.add(deviceDisplaceEntity);
                }
                if (!replacementsName.contains("qiChe")) {
                    qiChe.add(deviceDisplaceEntity);
                }
                if (!replacementsName.contains("other")) {
                    other.add(deviceDisplaceEntity);
                }
                List<DeviceDisplaceEntity> deviceDisplaces = (List<DeviceDisplaceEntity>) (Object) deviceDisplaceDao.getIBaseEntityByCondition("AND REPLACEMENT_ID=? AND DEL_FLAG=0", new Object[]{replacementEntity.getId()});
                for (DeviceDisplaceEntity deviceDisplace : deviceDisplaces) {
                    switch (deviceDisplace.getType()) {
                        //1-旧挖掘机，2-旧汽车，3-旧房屋，4-旧装载机，5-合同的其他情况
                        case 1:
                            wjj.add(deviceDisplace);
                            break;
                        case 2:
                            qiChe.add(deviceDisplace);
                            break;
                        case 3:
                            fangWu.add(deviceDisplace);
                            break;
                        case 4:
                            zzj.add(deviceDisplace);
                            break;
                        case 5:
                            other.add(deviceDisplace);
                            break;
                    }
                }
                //放入实体
                replacementEntity.setWjj(wjj);
                replacementEntity.setZzj(zzj);
                replacementEntity.setFangWu(fangWu);
                replacementEntity.setQiChe(qiChe);
                replacementEntity.setOther(other);
                entity.setReplacement(replacementEntity);
            }
        } else {
            ReplacementEntity replacementEntity = new ReplacementEntity();
            entity.setReplacement(replacementEntity);
        }
        //18合格证
        //19发票
        //20所有权转移证书
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("SELECT * FROM v_com_attach WHERE 1=1" + "\n");
        stringBuffer.append("AND moduleId=" + " '" + mainId + " ' AND ATTACH_MODULE=18");
        List<JSONObject> certificate = contractMainDao.queryForJsonList(stringBuffer.toString(), new Object[]{});
        if (certificate.size() == 0) {
            certificate = new ArrayList<JSONObject>();
        }
        StringBuffer stringBuffer2 = new StringBuffer();
        stringBuffer2.append("SELECT * FROM v_com_attach WHERE 1=1" + "\n");
        stringBuffer2.append("AND moduleId=" + " '" + mainId + " ' AND ATTACH_MODULE=20");
        List<JSONObject> ownershipTransfer = contractMainDao.queryForJsonList(stringBuffer2.toString(), new Object[]{});
        if (ownershipTransfer.size() == 0) {
            ownershipTransfer = new ArrayList<JSONObject>();
        }
        List<JSONObject> invoice = new ArrayList<JSONObject>();
        entity.setCertificate(certificate);
        entity.setInvoice(invoice);
        entity.setOwnershipTransfer(ownershipTransfer);
        JSONObject jsonObject = (JSONObject) JSON.toJSON(entity);
        return jsonObject;
    }


    //查询
    private JSONObject getContract(String mainId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        ContractEntity entity = new ContractEntity();
        ContractMainEntity contractMainEntity = (ContractMainEntity) contractMainDao.getIBaseEntityById(mainId);
        //查看购买方式是否为内部分期
        if (contractMainEntity.getBuyType().equals("内部分期")) {
            List<RepaymentEntity> repaymentFQList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND MAIN_ID=? AND PARENT_ID=0 AND TYPE=0  order by SORT_NO", new Object[]{mainId});//分期列表
            if (repaymentFQList != null && repaymentFQList.size() > 0) {
                for (int i = 0; i < repaymentFQList.size(); i++) {
                    RepaymentEntity repaymentEntity = repaymentFQList.get(i);
                    List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND PARENT_ID=? AND TYPE=0 order by SORT_NO", new Object[]{repaymentEntity.getId()});
                    repaymentEntity.setRepaymentParentList(repaymentParentList);
                    calRemainingArrears(repaymentEntity, repaymentParentList, "1");
                }
            }
            entity.setRepaymentFQList(repaymentFQList);
        } else {
            RepaymentEntity repaymentFQEntity = new RepaymentEntity();//内部分期
            List<RepaymentEntity> repaymentaFQEntityList = new ArrayList<RepaymentEntity>();
            repaymentaFQEntityList.add(repaymentFQEntity);
            entity.setRepaymentFQList(repaymentaFQEntityList);
        }
        //查看购买方式是否为内部分期并且有首付款分期
        if (contractMainEntity.getBuyType().equals("内部分期") && contractMainEntity.getHaveFQFirst() == 1) {
            List<RepaymentEntity> repaymentFQFirstList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND MAIN_ID=? AND PARENT_ID=0 AND TYPE=5  order by SORT_NO", new Object[]{mainId});//分期首付款分期
            if (repaymentFQFirstList != null && repaymentFQFirstList.size() > 0) {
                for (int i = 0; i < repaymentFQFirstList.size(); i++) {
                    RepaymentEntity repaymentEntity = repaymentFQFirstList.get(i);
                    List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND PARENT_ID=? AND TYPE=5 order by SORT_NO", new Object[]{repaymentEntity.getId()});
                    repaymentEntity.setRepaymentParentList(repaymentParentList);
                }
            }
            entity.setRepaymentFQFirstList(repaymentFQFirstList);

        } else {
            RepaymentEntity repaymentFQEntity = new RepaymentEntity();//内部分期
            List<RepaymentEntity> repaymentFQFirstList = new ArrayList<RepaymentEntity>();
            repaymentFQFirstList.add(repaymentFQEntity);
            entity.setRepaymentFQFirstList(repaymentFQFirstList);
        }
        //查看购买方式是否为融资租赁
        if (contractMainEntity.getBuyType().equals("融资租赁")) {
            List<RepaymentEntity> repaymentRZList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND MAIN_ID=? AND PARENT_ID=0 AND TYPE=2  order by SORT_NO", new Object[]{mainId});//分期列表
            if (null == repaymentRZList || repaymentRZList.size() == 0) {
                RepaymentEntity repaymentRZEntity = new RepaymentEntity();
                repaymentRZList.add(repaymentRZEntity);
            }
            if (repaymentRZList != null && repaymentRZList.size() > 0) {
                for (int i = 0; i < repaymentRZList.size(); i++) {
                    RepaymentEntity repaymentEntity = repaymentRZList.get(i);
                    List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND PARENT_ID=? AND TYPE=2 order by SORT_NO", new Object[]{repaymentEntity.getId()});
                    repaymentEntity.setRepaymentParentList(repaymentParentList);
                    if (contractMainEntity.getHaveDsdf() != 0) {
                        calRemainingArrears(repaymentEntity, repaymentParentList, "0");
                    }
                }
            }
            entity.setRepaymentRZList(repaymentRZList);
            //融资分期跟踪
            List<FinancingEntity> financingRZList = (List<FinancingEntity>) (Object) financingDao.getIBaseEntityByCondition(" AND MAIN_ID=? AND PARENT_ID='0' AND TYPE=2 ORDER BY SORT_NO ", new Object[]{mainId});
            if (null == financingRZList || financingRZList.size() == 0) {
                FinancingEntity financingEntity = new FinancingEntity();
                financingRZList.add(financingEntity);
            }
            for (int i = 0; i < financingRZList.size(); i++) {
                FinancingEntity financingEntity = financingRZList.get(i);
                List<FinancingEntity> repaymentParentList = (List<FinancingEntity>) (Object) financingDao.getIBaseEntityByCondition(" AND PARENT_ID=? AND TYPE=2  order by SORT_NO", new Object[]{financingEntity.getId()});
                financingEntity.setRepaymentParentList(repaymentParentList);
                if (StringUtils.isNotEmpty(financingEntity.getFinancingDate())) {
                    calRemainingArrears(financingEntity, repaymentParentList);
                }
            }
            entity.setFinancingRZList(financingRZList);

        } else {
            RepaymentEntity repaymentRZEntity = new RepaymentEntity();
            List<RepaymentEntity> repaymentaRZEntityList = new ArrayList<RepaymentEntity>();
            repaymentaRZEntityList.add(repaymentRZEntity);
            entity.setRepaymentRZList(repaymentaRZEntityList);
            //融资分期款跟踪
            FinancingEntity financingEntity = new FinancingEntity();
            List<FinancingEntity> financingRZList = new ArrayList<FinancingEntity>();
            financingRZList.add(financingEntity);
            entity.setFinancingRZList(financingRZList);

        }
        //查看购买方式是否为融资租赁打包
        if (contractMainEntity.getBuyType().equals("融资租赁打包")) {
            List<RepaymentEntity> repaymentRZDBList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND MAIN_ID=? AND PARENT_ID=0 AND TYPE=4  order by SORT_NO", new Object[]{mainId});//分期列表
            if (null == repaymentRZDBList || repaymentRZDBList.size() == 0) {
                RepaymentEntity repaymentRZDBEntity = new RepaymentEntity();
                repaymentRZDBList.add(repaymentRZDBEntity);
            }
            if (repaymentRZDBList != null && repaymentRZDBList.size() > 0) {
                for (int i = 0; i < repaymentRZDBList.size(); i++) {
                    RepaymentEntity repaymentEntity = repaymentRZDBList.get(i);
                    List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND PARENT_ID=? AND TYPE=4 order by SORT_NO", new Object[]{repaymentEntity.getId()});
                    repaymentEntity.setRepaymentParentList(repaymentParentList);
                    if (contractMainEntity.getHaveDsdf() != 0) {
                        calRemainingArrears(repaymentEntity, repaymentParentList, "0");
                    }
                }
            }
            entity.setRepaymentRZDBList(repaymentRZDBList);
            //融资分期跟踪
            List<FinancingEntity> financingRZDBList = (List<FinancingEntity>) (Object) financingDao.getIBaseEntityByCondition(" AND MAIN_ID=? AND PARENT_ID='0' AND TYPE=4  ORDER BY SORT_NO ", new Object[]{mainId});
            if (null == financingRZDBList || financingRZDBList.size() == 0) {
                FinancingEntity financingEntity = new FinancingEntity();
                financingRZDBList.add(financingEntity);
            }
            for (int i = 0; i < financingRZDBList.size(); i++) {
                FinancingEntity financingEntity = financingRZDBList.get(i);
                List<FinancingEntity> repaymentParentList = (List<FinancingEntity>) (Object) financingDao.getIBaseEntityByCondition(" AND PARENT_ID=? AND TYPE=4  order by SORT_NO", new Object[]{financingEntity.getId()});
                financingEntity.setRepaymentParentList(repaymentParentList);
                if (StringUtils.isNotEmpty(financingEntity.getFinancingDate())) {
                    calRemainingArrears(financingEntity, repaymentParentList);
                }
            }
            entity.setFinancingRZDBList(financingRZDBList);

        } else {
            RepaymentEntity repaymentRZDBEntity = new RepaymentEntity();
            List<RepaymentEntity> repaymentRZDBList = new ArrayList<RepaymentEntity>();
            repaymentRZDBList.add(repaymentRZDBEntity);
            entity.setRepaymentRZDBList(repaymentRZDBList);
            //融资分期款跟踪
            FinancingEntity financingEntity = new FinancingEntity();
            List<FinancingEntity> financingRZDBList = new ArrayList<FinancingEntity>();
            financingRZDBList.add(financingEntity);
            entity.setFinancingRZDBList(financingRZDBList);
        }
        //查看是否有垫款
        if (contractMainEntity.getHaveRepayment() == 1) {
            List<RepaymentEntity> repaymentDKList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND MAIN_ID=? AND PARENT_ID=0  AND TYPE=1  order by SORT_NO", new Object[]{mainId});//垫款列表
            if (repaymentDKList != null && repaymentDKList.size() > 0) {
                for (int i = 0; i < repaymentDKList.size(); i++) {
                    RepaymentEntity repaymentEntity = repaymentDKList.get(i);
                    List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND PARENT_ID=? AND TYPE=1 order by SORT_NO", new Object[]{repaymentEntity.getId()});
                    repaymentEntity.setRepaymentParentList(repaymentParentList);
                    calRemainingArrears(repaymentEntity, repaymentParentList, "1");
                }
            }
            entity.setRepaymentDKList(repaymentDKList);
        }
        //添加首付款信息
        List<RepaymentEntity> repaymentSFList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND MAIN_ID=? AND PARENT_ID=0 AND TYPE=3 order by SORT_NO", new Object[]{mainId});//首付款信息
        //添加首付款信息分期中的分期
        if (repaymentSFList != null && repaymentSFList.size() > 0) {
            for (int i = 0; i < repaymentSFList.size(); i++) {
                RepaymentEntity repaymentEntity = repaymentSFList.get(i);
                List<RepaymentEntity> repaymentParentList = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition(" AND PARENT_ID=? AND TYPE=3 order by SORT_NO", new Object[]{repaymentEntity.getId()});
                repaymentEntity.setRepaymentParentList(repaymentParentList);
                calRemainingArrears(repaymentEntity, repaymentParentList, "1");
            }
        }
        entity.setMain(contractMainEntity);
        entity.setRepaymentSFList(repaymentSFList);
        JSONObject jsonObject = (JSONObject) JSON.toJSON(entity);
        return jsonObject;
    }
    //还款页面保存方法
    public void saveFinancingList(JSONArray repaymentList, String repayDate, String createUserId, String createUserName, Integer type, String nowDate) {
        if (null != repaymentList && repaymentList.size() > 0) {
            for (int i = 0; i < repaymentList.size(); i++) {
                BigDecimal yqSum = new BigDecimal("0.00");
                String dateTime = "";
                net.sf.json.JSONObject FQJson = repaymentList.getJSONObject(i);
                BigDecimal qkRepayment = new BigDecimal(FQJson.getString("qkRepayment"));
                BigDecimal jrPenalty = new BigDecimal(FQJson.getString("jrPenalty"));
                BigDecimal yqRepayment = new BigDecimal(FQJson.getString("yqRepayment"));

                FinancingEntity financingEntity = (FinancingEntity) financingDao.getIBaseEntityById(FQJson.getString("id"));
                financingEntity.setRemainingArrears(new BigDecimal(FQJson.getString("sumqkmoney")).subtract(qkRepayment).compareTo(
                        new BigDecimal(0.00)) > 0 ? new BigDecimal(FQJson.getString("sumqkmoney")).subtract(qkRepayment) : new BigDecimal(0.00)
                );
                financingEntity.setJroverduePenalty(new BigDecimal(FQJson.getString("sumyqmoney")).subtract(yqRepayment).compareTo(
                        new BigDecimal(0.00)) > 0 ? new BigDecimal(FQJson.getString("sumyqmoney")).subtract(yqRepayment) : new BigDecimal(0.00)
                );
                financingEntity.setJrPenalty(jrPenalty.add(yqRepayment));
                financingEntity.setRemark(FQJson.getString("remark"));
                financingEntity.setHkType(financingEntity.getHkType());
                financingEntity.setRepaymentAttachName(FQJson.getString("repaymentAttachName"));
                financingEntity.setRepaymentAttachUrl(FQJson.getString("repaymentAttachUrl"));
                financingDao.update(financingEntity);
                yqSum = yqSum.add(financingEntity.getAdvancesMoney());
                dateTime = financingEntity.getAdvancesDate();
                //获取子list
                JSONArray repaymentParentList = new JSONArray();
                repaymentParentList = FQJson.getJSONArray("repaymentParentList");
                for (int j = 0; j < repaymentParentList.size(); j++) {
                    FinancingEntity repaymentParentEntity = (FinancingEntity) financingDao.getIBaseEntityById(repaymentParentList.getJSONObject(j).getString("id"));
                    if (null != repaymentParentEntity) {
                        repaymentParentEntity.setRemainingArrears(new BigDecimal(0.00));
                        repaymentParentEntity.setHkType(repaymentParentEntity.getHkType());
                        repaymentParentEntity.setRemark(repaymentParentList.getJSONObject(j).getString("remark"));
                        repaymentParentEntity.setRepaymentAttachName(repaymentParentList.getJSONObject(j).getString("repaymentAttachName"));
                        repaymentParentEntity.setRepaymentAttachUrl(repaymentParentList.getJSONObject(j).getString("repaymentAttachUrl"));
                        repaymentDao.update(repaymentParentEntity);
                        yqSum = yqSum.add(repaymentParentEntity.getAdvancesMoney());
                        dateTime = repaymentParentEntity.getAdvancesDate();
                    }

                }

                if (qkRepayment.compareTo(new BigDecimal(0.00)) > 0) {
                    FinancingEntity financingEntityHK = (FinancingEntity) financingDao.getIBaseEntityById(FQJson.getString("id"));
                    if (StringUtils.isBlank(financingEntityHK.getAdvancesDate()) && financingEntityHK.getAdvancesMoney().compareTo(new BigDecimal(0.00)) == 0) {

                        if (StringUtils.isNotEmpty(FQJson.getString("repaymentDate2"))) {
                            financingEntityHK.setAdvancesDate(FQJson.getString("repaymentDate2"));
                        }
                        if (StringUtils.isNotEmpty(FQJson.getString("remark2"))) {
                            financingEntityHK.setRemark(FQJson.getString("remark2"));
                        }
                        financingEntityHK.setAdvancesMoney(qkRepayment);
                        financingEntityHK.setHkType(1);
                        financingEntityHK.setType(type);
                        financingEntityHK.setCreateUserId(createUserId);
                        financingEntityHK.setCreateUserName(createUserName);
                        financingEntityHK.setCreateDate(DateUtils.nowSFByString(repaymentDao.getCurrentTime()));
                        financingEntityHK.setCreateTime(repaymentDao.getCurrentTime());
                        financingDao.update(financingEntityHK);
                        yqSum = yqSum.add(financingEntityHK.getAdvancesMoney());
                        dateTime = financingEntityHK.getAdvancesDate();
                    } else {
                        //查询跟踪款
                        List<FinancingEntity> repaymentParentListHK = (List<FinancingEntity>) (Object) financingDao.getIBaseEntityByCondition("AND PARENT_ID=?  order by SORT_NO", new Object[]{FQJson.getString("id")});
                        //查询最后一条子list
                        FinancingEntity financingEntityParentHK = new FinancingEntity();
                        if (repaymentParentListHK != null && repaymentParentListHK.size() > 0) {
                            financingEntityParentHK.setSortNo(repaymentParentListHK.size());
                        } else {
                            financingEntityParentHK.setSortNo(0);
                        }
                        financingEntityParentHK.setMainId(FQJson.getString("mainId"));
                        financingEntityParentHK.setParentId(FQJson.getString("id"));
                        financingEntityParentHK.setFinancingDate(FQJson.getString("financingDate"));
                        financingEntityParentHK.setFinancingMoney(new BigDecimal(FQJson.getString("financingMoney")));
                        financingEntityParentHK.setAdvancesMoney(qkRepayment);
                        financingEntityParentHK.setHkType(1);
                        financingEntityParentHK.setType(type);
                        if (StringUtils.isNotEmpty(FQJson.getString("repaymentDate2"))) {
                            financingEntityParentHK.setAdvancesDate(FQJson.getString("repaymentDate2"));
                        }
                        if (StringUtils.isNotEmpty(FQJson.getString("remark2"))) {
                            financingEntityParentHK.setRemark(FQJson.getString("remark2"));
                        }
                        financingEntityParentHK.setCreateUserId(createUserId);
                        financingEntityParentHK.setCreateUserName(createUserName);
                        financingEntityParentHK.setCreateDate(DateUtils.nowSFByString(repaymentDao.getCurrentTime()));
                        financingEntityParentHK.setCreateTime(repaymentDao.getCurrentTime());
                        financingDao.add(financingEntityParentHK);
                        yqSum = yqSum.add(financingEntityParentHK.getAdvancesMoney());
                        dateTime = financingEntityParentHK.getAdvancesDate();
                    }
                }
                if (yqRepayment.compareTo(new BigDecimal(0.00)) > 0) {
                    FinancingEntity financingEntityHK = (FinancingEntity) financingDao.getIBaseEntityById(FQJson.getString("id"));
                    if (StringUtils.isBlank(financingEntityHK.getAdvancesDate()) && financingEntityHK.getAdvancesMoney().compareTo(new BigDecimal(0.00)) == 0) {
                        if (StringUtils.isNotEmpty(FQJson.getString("repaymentDate2"))) {
                            financingEntityHK.setAdvancesDate(FQJson.getString("repaymentDate2"));
                        }
                        if (StringUtils.isNotEmpty(FQJson.getString("remark2"))) {
                            financingEntityHK.setRemark(FQJson.getString("remark2"));
                        }
                        financingEntityHK.setAdvancesMoney(qkRepayment.add(yqRepayment));
                        financingEntityHK.setHkType(2);
                        financingEntityHK.setRemark(FQJson.getString("remark") + "逾期罚息还款" + yqRepayment + "元");
                        financingEntityHK.setType(type);
                        financingEntityHK.setCreateUserId(createUserId);
                        financingEntityHK.setCreateUserName(createUserName);
                        financingEntityHK.setCreateDate(DateUtils.nowSFByString(repaymentDao.getCurrentTime()));
                        financingEntityHK.setCreateTime(repaymentDao.getCurrentTime());
                        financingDao.update(financingEntityHK);
                        yqSum = yqSum.add(financingEntityHK.getAdvancesMoney());
                        dateTime = financingEntityHK.getAdvancesDate();
                    } else {
                        //查询跟踪款
                        List<FinancingEntity> repaymentParentListHK = (List<FinancingEntity>) (Object) financingDao.getIBaseEntityByCondition("AND PARENT_ID=?  order by SORT_NO", new Object[]{FQJson.getString("id")});
                        //查询最后一条子list
                        FinancingEntity financingEntityParentHK = new FinancingEntity();
                        if (repaymentParentListHK != null && repaymentParentListHK.size() > 0) {
                            financingEntityParentHK.setSortNo(repaymentParentListHK.size());
                        } else {
                            financingEntityParentHK.setSortNo(0);
                        }
                        financingEntityParentHK.setMainId(FQJson.getString("mainId"));
                        financingEntityParentHK.setParentId(FQJson.getString("id"));
                        financingEntityParentHK.setFinancingDate(FQJson.getString("financingDate"));
                        financingEntityParentHK.setFinancingMoney(new BigDecimal(FQJson.getString("financingMoney")));
                        financingEntityParentHK.setAdvancesMoney(yqRepayment);
                        financingEntityParentHK.setHkType(2);
                        if (StringUtils.isNotEmpty(FQJson.getString("repaymentDate2"))) {
                            financingEntityParentHK.setAdvancesDate(FQJson.getString("repaymentDate2"));
                        }
                        if (StringUtils.isNotEmpty(FQJson.getString("remark2"))) {
                            financingEntityParentHK.setRemark(FQJson.getString("remark2"));
                        }
                        financingEntityParentHK.setRemark(financingEntityParentHK.getRemark() + "逾期罚息还款" + yqRepayment + "元");
                        financingEntityParentHK.setType(type);

                        financingEntityParentHK.setCreateUserId(createUserId);
                        financingEntityParentHK.setCreateUserName(createUserName);
                        financingEntityParentHK.setCreateDate(DateUtils.nowSFByString(repaymentDao.getCurrentTime()));
                        financingEntityParentHK.setCreateTime(repaymentDao.getCurrentTime());
                        financingDao.add(financingEntityParentHK);
                        yqSum = yqSum.add(financingEntityParentHK.getAdvancesMoney());
                        dateTime = financingEntityParentHK.getAdvancesDate();
                    }
                }

                //判断逾期
                if (financingEntity.getFinancingDate().compareTo(nowDate) <= 0) {
                    getOverDue(FQJson.getString("mainId"), yqSum, dateTime, financingEntity.getFinancingMoney(), financingEntity.getFinancingDate(), nowDate, financingEntity.getJroverduePenalty(),financingEntity.getRemainingArrears());
                }
            }
        }
    }

    public void saveRepaymentList(JSONArray repaymentList, String repayDate, String createUserId, String createUserName, Integer type, String nowDate) {
        if (null != repaymentList && repaymentList.size() > 0) {
            for (int i = 0; i < repaymentList.size(); i++) {
                BigDecimal yqSum = new BigDecimal("0.00");
                String dateTime = "";
                net.sf.json.JSONObject FQJson = repaymentList.getJSONObject(i);
                BigDecimal qkRepayment = new BigDecimal(FQJson.getString("qkRepayment"));
                BigDecimal yqRepayment = new BigDecimal(FQJson.getString("yqRepayment"));
                BigDecimal gsPenalty = new BigDecimal(FQJson.getString("gsPenalty"));
                RepaymentEntity repaymentEntity = (RepaymentEntity) repaymentDao.getIBaseEntityById(FQJson.getString("id"));
                repaymentEntity.setOverduePenalty(new BigDecimal(FQJson.getString("sumyqmoney")).subtract(yqRepayment).compareTo(new BigDecimal(0.00)) > 0 ?
                        new BigDecimal(FQJson.getString("sumyqmoney")).subtract(yqRepayment) : new BigDecimal(0.00));
                repaymentEntity.setRemainingArrears(new BigDecimal(FQJson.getString("sumqkmoney")).subtract(qkRepayment).compareTo(new BigDecimal(0.00)) > 0 ?
                        new BigDecimal(FQJson.getString("sumqkmoney")).subtract(qkRepayment) : new BigDecimal(0.00));
                repaymentEntity.setCdRemainingArrears(qkRepayment.add(repaymentEntity.getCdRemainingArrears()));
                repaymentEntity.setCdOverduePenalty(yqRepayment.add(repaymentEntity.getCdOverduePenalty()));
                repaymentEntity.setOverduePenaltyTotal(new BigDecimal(FQJson.getString("overduePenaltyTotal")));
                repaymentEntity.setRemark(FQJson.getString("remark"));
                repaymentEntity.setHkType(repaymentEntity.getHkType());
                repaymentEntity.setGsPenalty(gsPenalty.add(yqRepayment));
                repaymentEntity.setRepaymentAttachName(FQJson.getString("repaymentAttachName"));
                repaymentEntity.setRepaymentAttachUrl(FQJson.getString("repaymentAttachUrl"));
                repaymentDao.update(repaymentEntity);
                yqSum = yqSum.add(repaymentEntity.getRepaymentAmount());
                dateTime = repaymentEntity.getActualRepaymentDate();
                //获取子list
                JSONArray repaymentParentList = new JSONArray();
                repaymentParentList = FQJson.getJSONArray("repaymentParentList");
                for (int j = 0; j < repaymentParentList.size(); j++) {
                    RepaymentEntity repaymentParentEntity = (RepaymentEntity) repaymentDao.getIBaseEntityById(repaymentParentList.getJSONObject(j).getString("id"));
                    if (null != repaymentParentEntity) {
                        repaymentParentEntity.setRemainingArrears(new BigDecimal(0.00));
                        repaymentParentEntity.setOverduePenalty(new BigDecimal(0.00));
                        repaymentParentEntity.setHkType(repaymentParentEntity.getHkType());
                        repaymentParentEntity.setRemark(repaymentParentList.getJSONObject(j).getString("remark"));
                        repaymentParentEntity.setRepaymentAttachName(repaymentParentList.getJSONObject(j).getString("repaymentAttachName"));
                        repaymentParentEntity.setRepaymentAttachUrl(repaymentParentList.getJSONObject(j).getString("repaymentAttachUrl"));
                        repaymentDao.update(repaymentParentEntity);
                        yqSum = yqSum.add(repaymentParentEntity.getRepaymentAmount());
                        dateTime = repaymentParentEntity.getActualRepaymentDate();
                    }
                }
                if (qkRepayment.compareTo(new BigDecimal(0.00)) > 0) {
                    RepaymentEntity repaymentEntityHK = (RepaymentEntity) repaymentDao.getIBaseEntityById(FQJson.getString("id"));
                    if (StringUtils.isBlank(repaymentEntityHK.getActualRepaymentDate()) && repaymentEntityHK.getRepaymentAmount().compareTo(new BigDecimal(0.00)) == 0) {
                        if (StringUtils.isNotEmpty(FQJson.getString("repaymentDate2"))) {
                            repaymentEntityHK.setActualRepaymentDate(FQJson.getString("repaymentDate2"));
                        }
                        if (StringUtils.isNotEmpty(FQJson.getString("remark2"))) {
                            repaymentEntityHK.setRemark(FQJson.getString("remark2"));
                        }
                        repaymentEntityHK.setRepaymentAmount(qkRepayment);
                        repaymentEntityHK.setHkType(1);
                        repaymentEntityHK.setCreateUserId(createUserId);
                        repaymentEntityHK.setType(type);
                        repaymentEntityHK.setCreateUserName(createUserName);
                        repaymentEntityHK.setCreateDate(DateUtils.nowSFByString(repaymentDao.getCurrentTime()));
                        repaymentEntityHK.setCreateTime(repaymentDao.getCurrentTime());
                        yqSum = yqSum.add(repaymentEntityHK.getRepaymentAmount());
                        dateTime = repaymentEntityHK.getActualRepaymentDate();
                        repaymentDao.update(repaymentEntityHK);
                    } else {
                        //查询跟踪款
                        List<RepaymentEntity> repaymentParentListHK = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND PARENT_ID=?  order by SORT_NO", new Object[]{FQJson.getString("id")});
                        //查询最后一条子list
                        RepaymentEntity repaymentEntityParentHK = new RepaymentEntity();
                        if (repaymentParentListHK != null && repaymentParentListHK.size() > 0) {
                            repaymentEntityParentHK.setSortNo(repaymentParentListHK.size());
                        } else {
                            repaymentEntityParentHK.setSortNo(0);
                        }
                        repaymentEntityParentHK.setMainId(FQJson.getString("mainId"));
                        repaymentEntityParentHK.setHkType(1);
                        repaymentEntityParentHK.setType(type);
                        repaymentEntityParentHK.setParentId(FQJson.getString("id"));
                        repaymentEntityParentHK.setRepaymentDate(FQJson.getString("repaymentDate"));
                        repaymentEntityParentHK.setRepaymentAmount(qkRepayment);
                        repaymentEntityParentHK.setRemainingArrears(new BigDecimal(0.00));
                        repaymentEntityParentHK.setOverduePenalty(new BigDecimal(0.00));
                        repaymentEntityParentHK.setTotal(new BigDecimal(FQJson.getString("total")));
                        repaymentEntityParentHK.setPrincipal(new BigDecimal(FQJson.getString("principal")));
                        repaymentEntityParentHK.setInterest(new BigDecimal(FQJson.getString("interest")));
                        repaymentEntityParentHK.setContractRepaymentAmount(new BigDecimal(FQJson.getString("contractRepaymentAmount")));
                        repaymentEntityParentHK.setCreateUserId(createUserId);
                        repaymentEntityParentHK.setCreateUserName(createUserName);
                        if (StringUtils.isNotEmpty(FQJson.getString("repaymentDate2"))) {
                            repaymentEntityParentHK.setActualRepaymentDate(FQJson.getString("repaymentDate2"));
                        }
                        if (StringUtils.isNotEmpty(FQJson.getString("remark2"))) {
                            repaymentEntityParentHK.setRemark(FQJson.getString("remark2"));
                        }
                        repaymentEntityParentHK.setCreateDate(DateUtils.nowSFByString(repaymentDao.getCurrentTime()));
                        repaymentEntityParentHK.setCreateTime(repaymentDao.getCurrentTime());
                        repaymentDao.add(repaymentEntityParentHK);
                        yqSum = yqSum.add(repaymentEntityParentHK.getRepaymentAmount());
                        dateTime = repaymentEntityParentHK.getActualRepaymentDate();
                    }
                }
                if (yqRepayment.compareTo(new BigDecimal(0.00)) > 0) {
                    RepaymentEntity repaymentEntityHK = (RepaymentEntity) repaymentDao.getIBaseEntityById(FQJson.getString("id"));
                    if (StringUtils.isBlank(repaymentEntityHK.getActualRepaymentDate()) && repaymentEntityHK.getRepaymentAmount().compareTo(new BigDecimal(0.00)) == 0) {
                        if (StringUtils.isNotEmpty(FQJson.getString("repaymentDate2"))) {
                            repaymentEntityHK.setActualRepaymentDate(FQJson.getString("repaymentDate2"));
                        }
                        if (StringUtils.isNotEmpty(FQJson.getString("remark2"))) {
                            repaymentEntityHK.setRemark(FQJson.getString("remark2"));
                        }
                        repaymentEntityHK.setRepaymentAmount(yqRepayment);
                        repaymentEntityHK.setCreateUserId(createUserId);
                        repaymentEntityHK.setType(type);
                        repaymentEntityHK.setCreateUserName(createUserName);
                        repaymentEntityHK.setCreateDate(DateUtils.nowSFByString(repaymentDao.getCurrentTime()));
                        repaymentEntityHK.setCreateTime(repaymentDao.getCurrentTime());
                        repaymentEntityHK.setHkType(2);
                        repaymentEntityHK.setRemark(FQJson.getString("remark") + "逾期罚息还款" + yqRepayment + "元");
                        repaymentDao.update(repaymentEntityHK);
                        yqSum = yqSum.add(repaymentEntityHK.getRepaymentAmount());
                        dateTime = repaymentEntityHK.getActualRepaymentDate();
                    } else {
                        //查询跟踪款
                        List<RepaymentEntity> repaymentParentListHK = (List<RepaymentEntity>) (Object) repaymentDao.getIBaseEntityByCondition("AND PARENT_ID=?  order by SORT_NO", new Object[]{FQJson.getString("id")});
                        //查询最后一条子list
                        RepaymentEntity repaymentEntityParentHK = new RepaymentEntity();
                        if (repaymentParentListHK != null && repaymentParentListHK.size() > 0) {
                            repaymentEntityParentHK.setSortNo(repaymentParentListHK.size());
                        } else {
                            repaymentEntityParentHK.setSortNo(0);
                        }
                        if (StringUtils.isNotEmpty(FQJson.getString("repaymentDate2"))) {
                            repaymentEntityParentHK.setActualRepaymentDate(FQJson.getString("repaymentDate2"));
                        }
                        if (StringUtils.isNotEmpty(FQJson.getString("remark2"))) {
                            repaymentEntityParentHK.setRemark(FQJson.getString("remark2"));
                        }
                        repaymentEntityParentHK.setHkType(2);
                        repaymentEntityParentHK.setMainId(FQJson.getString("mainId"));
                        repaymentEntityParentHK.setType(type);
                        repaymentEntityParentHK.setParentId(FQJson.getString("id"));
                        repaymentEntityParentHK.setRepaymentDate(FQJson.getString("repaymentDate"));
                        repaymentEntityParentHK.setRepaymentAmount(yqRepayment);
                        repaymentEntityParentHK.setRemark(repaymentEntityParentHK.getRemark() + "逾期罚息还款" + yqRepayment + "元");
                        repaymentEntityParentHK.setRemainingArrears(new BigDecimal(0.00));
                        repaymentEntityParentHK.setOverduePenalty(new BigDecimal(0.00));
                        repaymentEntityParentHK.setTotal(new BigDecimal(FQJson.getString("total")));
                        repaymentEntityParentHK.setPrincipal(new BigDecimal(FQJson.getString("principal")));
                        repaymentEntityParentHK.setInterest(new BigDecimal(FQJson.getString("interest")));
                        repaymentEntityParentHK.setContractRepaymentAmount(new BigDecimal(FQJson.getString("contractRepaymentAmount")));
                        repaymentEntityParentHK.setCreateUserId(createUserId);
                        repaymentEntityParentHK.setCreateUserName(createUserName);

                        repaymentEntityParentHK.setCreateDate(DateUtils.nowSFByString(repaymentDao.getCurrentTime()));
                        repaymentEntityParentHK.setCreateTime(repaymentDao.getCurrentTime());
                        repaymentDao.add(repaymentEntityParentHK);
                        yqSum = yqSum.add(repaymentEntityParentHK.getRepaymentAmount());
                        dateTime = repaymentEntityParentHK.getActualRepaymentDate();
                    }
                }
                //判断逾期
                if (repaymentEntity.getRepaymentDate().compareTo(nowDate) <= 0) {
                    if (repaymentEntity.getType() == 2 || repaymentEntity.getType() == 4) {
                        getOverDue(FQJson.getString("mainId"), yqSum, dateTime, repaymentEntity.getContractRepaymentAmount(), repaymentEntity.getRepaymentDate(), nowDate, repaymentEntity.getOverduePenalty(),repaymentEntity.getRemainingArrears());
                    } else {
                        getOverDue(FQJson.getString("mainId"), yqSum, dateTime, repaymentEntity.getTotal(), repaymentEntity.getRepaymentDate(), nowDate, repaymentEntity.getOverduePenalty(),repaymentEntity.getRemainingArrears());

                    }
                }
            }
        }
    }

    //发送短信
    private JSONObject getMessage(MessageEntity messageEntity, MessageReceiverEntity messageReceiverEntity) {
        String userId = messageEntity.getCreateUserId();
        UserEntity userEntity = userDao.getById(userId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("id", messageEntity.getId());
        jsonObject.put("createUserId", userId);
        jsonObject.put("createUserName", userEntity.getName());
        jsonObject.put("createTime", messageEntity.getCreateTime());
        jsonObject.put("content", messageEntity.getContent());
        jsonObject.put("mainId", messageEntity.getMainId());
        jsonObject.put("delFlag", messageEntity.getDelFlag());
        jsonObject.put("openTitle", messageEntity.getOpenTitle());
        jsonObject.put("openUrl", messageEntity.getOpenUrl());
        jsonObject.put("messageType", messageEntity.getMessageType());
        jsonObject.put("receiverId", messageReceiverEntity.getId());
        jsonObject.put("receiverUserId", messageReceiverEntity.getUserId());
        jsonObject.put("receiverUserType", messageReceiverEntity.getUserType());
        jsonObject.put("receiverReadFlag", messageReceiverEntity.getReadFlag());
        return jsonObject;
    }

    //计算逾期金额
    public static int between_days(String a, String b) {

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// 自定义时间格式

        Calendar calendar_a = Calendar.getInstance();// 获取日历对象
        Calendar calendar_b = Calendar.getInstance();

        Date date_a = null;
        Date date_b = null;

        try {
            date_a = simpleDateFormat.parse(a);//字符串转Date
            date_b = simpleDateFormat.parse(b);
            calendar_a.setTime(date_a);// 设置日历
            calendar_b.setTime(date_b);
        } catch (ParseException e) {
            e.printStackTrace();//格式化异常
        }

        long time_a = calendar_a.getTimeInMillis();
        long time_b = calendar_b.getTimeInMillis();

        long between_days = (time_b - time_a) / (1000 * 3600 * 24);//计算相差天数
        return Integer.parseInt(String.valueOf(between_days));
    }

    //计算剩余欠款逾期罚息 JSON 销售合同
    public void calRemainingArrears(JSONObject jsonObject, List<JSONObject> repaymentParentList, String type) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        BigDecimal autalRepay = jsonObject.getBigDecimal("repaymentAmount");
        BigDecimal sumqkmoney = new BigDecimal(0.00);
        BigDecimal sumyqmoney = new BigDecimal(0.00);
        jsonObject.put("remainingArrears", new BigDecimal(0));
        jsonObject.put("overduePenalty", new BigDecimal(0));
        if (repaymentParentList.size() > 0) {
            for (int j = 0; j < repaymentParentList.size(); j++) {
                repaymentParentList.get(j).put("remainingArrears", new BigDecimal(0));
                repaymentParentList.get(j).put("overduePenalty", new BigDecimal(0));
                if (repaymentParentList.get(j).getInteger("hkType") != 2 && repaymentParentList.get(j).getInteger("hkType") != 3) {
                    autalRepay = repaymentParentList.get(j).getBigDecimal("repaymentAmount").add(autalRepay);
                }
            }
            if (between_days(jsonObject.getString("repaymentDate"), sdf.format(new Date())) >= 0) {
                if (type.equals("0")) {
                    sumqkmoney = sumqkmoney.add(jsonObject.getBigDecimal("contractRepaymentAmount").subtract(autalRepay).compareTo(new BigDecimal(0.00)) > 0 ? jsonObject.getBigDecimal("contractRepaymentAmount").subtract(autalRepay) : new BigDecimal(0));
                } else {
                    sumqkmoney = sumqkmoney.add(jsonObject.getBigDecimal("total").subtract(autalRepay).compareTo(new BigDecimal(0.00)) > 0 ? jsonObject.getBigDecimal("total").subtract(autalRepay) : new BigDecimal(0));
                }
            }
        } else {
            if (between_days(jsonObject.getString("repaymentDate"), sdf.format(new Date())) >= 0) {
                if (type.equals("0")) {
                    sumqkmoney = sumqkmoney.add(jsonObject.getBigDecimal("contractRepaymentAmount").subtract(autalRepay).compareTo(new BigDecimal(0.00)) > 0 ? jsonObject.getBigDecimal("contractRepaymentAmount").subtract(autalRepay) : new BigDecimal(0));

                } else {
                    sumqkmoney = sumqkmoney.add(jsonObject.getBigDecimal("total").subtract(autalRepay).compareTo(new BigDecimal(0.00)) > 0 ? jsonObject.getBigDecimal("total").subtract(autalRepay) : new BigDecimal(0));
                }
            }
        }
        //先算剩余欠款
        jsonObject.put("remainingArrears", sumqkmoney.setScale(2, BigDecimal.ROUND_HALF_UP));
        jsonObject.put("sumqkmoney", sumqkmoney.setScale(2, BigDecimal.ROUND_HALF_UP));
        //根据剩余欠款算逾期罚息
        calOverduePenalty(jsonObject, repaymentParentList, type);

    }

    public void calOverduePenalty(JSONObject jsonObject, List<JSONObject> repaymentParentList, String type) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //约定还款日期
        String repaymentDate = jsonObject.getString("repaymentDate");
        //约定还款金额
        BigDecimal repayMentMoney = null;
        //判断是否计算逾期
        Boolean yq = false;
        //获取冲抵罚息
        BigDecimal cdOverdue = jsonObject.getBigDecimal("cdOverduePenalty");
        if (type.equals("0")) {
            repayMentMoney = jsonObject.getBigDecimal("contractRepaymentAmount");
        } else {
            repayMentMoney = jsonObject.getBigDecimal("total");
        }
        String nowDate = sdf.format(new Date());
        //剩余总欠款
        BigDecimal remainingArrears = jsonObject.getBigDecimal("remainingArrears");
        //最后实际还款日期
        String lastActualRepaymentDate = nowDate;
        BigDecimal overduePenalty = new BigDecimal(0.00);

        BigDecimal everyRemainingArrear = new BigDecimal(0.00);

        //判断剩余欠款的实际还款有几条
        int sumRepay = 0;
        BigDecimal yhOver = new BigDecimal(0.00);
        ;
        //判断主的是逾期罚息还是剩余欠款
        if (jsonObject.getInteger("hkType") != 2 && jsonObject.getInteger("hkType") != 3) {
            sumRepay = sumRepay + 1;
            everyRemainingArrear = everyRemainingArrear.add(jsonObject.getBigDecimal("repaymentAmount"));
            if (StringUtils.isNotEmpty(jsonObject.getString("actualRepaymentDate"))) {
                lastActualRepaymentDate = jsonObject.getString("actualRepaymentDate");

            }
            if (between_days(repaymentDate, lastActualRepaymentDate) > 7) {
                yq = true;
            }
        } else {
            yhOver = yhOver.add(jsonObject.getBigDecimal("repaymentAmount"));
        }
        //主的剩余欠款
        jsonObject.put("everyRemainingArrear", repayMentMoney.subtract(everyRemainingArrear));
        jsonObject.put("everyOverduePenalty", new BigDecimal(0.00));
        int jsOverdue = 0;

        if (between_days(repaymentDate, nowDate) > 0) {
            if (null != repaymentParentList && repaymentParentList.size() > 0) {

                int sumQkHk = 0;
                for (int i = 0; i < repaymentParentList.size(); i++) {
                    if (repaymentParentList.get(i).getInteger("hkType") != 2 && repaymentParentList.get(i).getInteger("hkType") != 3) {
                        sumRepay = sumRepay + 1;
                        sumQkHk = i;
                        //计算每期剩余欠款,便于计算每期的逾期罚息
                        everyRemainingArrear = everyRemainingArrear.add(repaymentParentList.get(i).getBigDecimal("repaymentAmount"));
                        if (between_days(repaymentDate, repaymentParentList.get(i).getString("actualRepaymentDate")) > 7) {
                            yq = true;
                        }
                    }
                    repaymentParentList.get(i).put("everyOverduePenalty", new BigDecimal(0.00));

                    repaymentParentList.get(i).put("everyRemainingArrear", repayMentMoney.subtract(everyRemainingArrear));
                }
                //实际还款为欠款还款的最后一条的日期
                lastActualRepaymentDate = repaymentParentList.get(sumQkHk).getString("actualRepaymentDate");
            }
        }
        //判断是否计算逾期
        if ((between_days(repaymentDate, nowDate) > 0 && yq)
                || (remainingArrears.compareTo(new BigDecimal(0.00)) > 0 && between_days(repaymentDate, nowDate) > 7)
        ) {
            //判断最后一条的日期与约定还款日期的大小{当前日期-约定日期)*0.0007*总剩余欠款

            //判断最后一条的日期与约定还款日期的大小{当前日期-约定日期)*0.0007*总剩余欠款
            if (between_days(lastActualRepaymentDate, repaymentDate) >= 0 || StringUtils.isBlank(jsonObject.getString("actualRepaymentDate"))) {
                //（当前日期-约定日期）*总剩余欠款*0.0007
                overduePenalty = overduePenalty.add(remainingArrears.multiply(new BigDecimal(between_days(repaymentDate, nowDate) * 0.0007))).setScale(2, BigDecimal.ROUND_HALF_UP);
                //其他为0，最后一条为逾期罚息
                if (null != repaymentParentList && repaymentParentList.size() > 0) {
                    jsonObject.put("everyOverduePenalty", new BigDecimal(0.00));
                    for (int i = 0; i < repaymentParentList.size(); i++) {
                        repaymentParentList.get(i).put("everyOverduePenalty", new BigDecimal(0.00));
                    }
                } else {
                    jsonObject.put("everyOverduePenalty", overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));
                }
            } else {
                //判断计算罚息的期数是否包含主的，如果包含，主的为（本期-约定）*上期欠款*0.0007，其他期数为（本期-上期）
                if (between_days(repaymentDate, jsonObject.getString("actualRepaymentDate")) > 0) {
                    jsOverdue = jsOverdue + 1;
                    overduePenalty = overduePenalty.add(repayMentMoney.multiply(
                            new BigDecimal(between_days(repaymentDate, jsonObject.getString("actualRepaymentDate")) * 0.0007))).setScale(2, BigDecimal.ROUND_HALF_UP);
                    //如果还款只有一条并且是主的，那么就加上最后的那个计算
                    if (sumRepay == 1) {
                        //最后加上（当前日期-最后一天日期）*所有欠款*0.0007
                        overduePenalty = overduePenalty.add(remainingArrears.multiply(new BigDecimal(between_days(lastActualRepaymentDate, nowDate) * 0.0007))).setScale(2, BigDecimal.ROUND_HALF_UP);
                    }
                    //主的的罚息

                    jsonObject.put("everyOverduePenalty", overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));

                }
                if (null != repaymentParentList && repaymentParentList.size() > 0) {
                    if (jsOverdue == 1) {
                        //主的计算
                        for (int i = 0; i < repaymentParentList.size(); i++) {
                            repaymentParentList.get(i).put("everyOverduePenalty", new BigDecimal(0.00));
                            if (repaymentParentList.get(i).getInteger("hkType") == 2 || repaymentParentList.get(i).getInteger("hkType") == 3) {
                                yhOver = yhOver.add(repaymentParentList.get(i).getBigDecimal("repaymentAmount"));
                            }
                            if (between_days(repaymentDate, repaymentParentList.get(i).getString("actualRepaymentDate")) > 0) {
                                //判断是否是多期,其他期数为（本期-上期）*上期欠款*0.0007

                                if (i == 0) {
                                    //i==0;本期-主的
                                    overduePenalty = overduePenalty.add(jsonObject.getBigDecimal("everyRemainingArrear").multiply(
                                            new BigDecimal(between_days(jsonObject.getString("actualRepaymentDate"), repaymentParentList.get(i).getString("actualRepaymentDate")) * 0.0007))).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    repaymentParentList.get(i).put("everyOverduePenalty", overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));


                                } else {
                                    //获取上一期不是逾期罚息的那一期
                                    int qkDate = 0;
                                    for (int j = i - 1; j >= 0; j--) {
                                        if (repaymentParentList.get(j).getInteger("hkType") != 2 && repaymentParentList.get(j).getInteger("hkType") != 3) {
                                            qkDate = j;
                                            break;
                                        }
                                    }
                                    overduePenalty = overduePenalty.add(repaymentParentList.get(qkDate).getBigDecimal("everyRemainingArrear").multiply(
                                            new BigDecimal(between_days(repaymentParentList.get(qkDate).getString("actualRepaymentDate"), repaymentParentList.get(i).getString("actualRepaymentDate")) * 0.0007))).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    repaymentParentList.get(i).put("everyOverduePenalty", overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));
                                }
                            }
                        }
                    } else {
                        jsonObject.put("everyOverduePenalty", new BigDecimal(0.00));

                        //主的不进行计算逾期
                        for (int i = 0; i < repaymentParentList.size(); i++) {
                            repaymentParentList.get(i).put("everyOverduePenalty", new BigDecimal(0.00));
                            if (repaymentParentList.get(i).getInteger("hkType") == 2 || repaymentParentList.get(i).getInteger("hkType") == 3) {
                                yhOver = yhOver.add(repaymentParentList.get(i).getBigDecimal("repaymentAmount"));
                            }
                            if (between_days(repaymentDate, repaymentParentList.get(i).getString("actualRepaymentDate")) > 0) {
                                //计算的第一期为（本期-约定）*本期欠款*0.0007，其他期数为（本期-上期）
                                jsOverdue = jsOverdue + 1;
                                if (jsOverdue == 1) {
                                    if (i == 0) {
                                        //上期欠款为主的
                                        overduePenalty = overduePenalty.add(jsonObject.getBigDecimal("everyRemainingArrear").multiply(
                                                new BigDecimal(between_days(repaymentDate, repaymentParentList.get(i).getString("actualRepaymentDate")) * 0.0007))).setScale(2, BigDecimal.ROUND_HALF_UP);

                                        repaymentParentList.get(i).put("everyOverduePenalty", overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));


                                    } else {
                                        int qkDate = 0;
                                        for (int j = i - 1; j >= 0; j--) {
                                            if (repaymentParentList.get(j).getInteger("hkType") != 2 && repaymentParentList.get(j).getInteger("hkType") != 3) {
                                                qkDate = j;
                                                break;
                                            }
                                        }
                                        overduePenalty = overduePenalty.add(repaymentParentList.get(qkDate).getBigDecimal("everyRemainingArrear").multiply(
                                                new BigDecimal(between_days(repaymentDate, repaymentParentList.get(i).getString("actualRepaymentDate")) * 0.0007))).setScale(2, BigDecimal.ROUND_HALF_UP);
                                        repaymentParentList.get(i).put("everyOverduePenalty", overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));

                                    }
                                } else {
                                    int qkDate = 0;
                                    for (int j = i - 1; j >= 0; j--) {
                                        if (repaymentParentList.get(j).getInteger("hkType") != 2 && repaymentParentList.get(j).getInteger("hkType") != 3) {
                                            qkDate = j;
                                            break;
                                        }
                                    }
                                    overduePenalty = overduePenalty.add(repaymentParentList.get(qkDate).getBigDecimal("everyRemainingArrear").multiply(
                                            new BigDecimal(between_days(repaymentParentList.get(qkDate).getString("actualRepaymentDate"), repaymentParentList.get(i).getString("actualRepaymentDate")) * 0.0007)));
                                    repaymentParentList.get(i).put("everyOverduePenalty", overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));

                                }
                            }
                        }
                    }
                    //最后加上（当前日期-最后一天日期）*所有欠款*0.0007
                    overduePenalty = overduePenalty.add(remainingArrears.multiply(new BigDecimal(between_days(lastActualRepaymentDate, nowDate) * 0.0007))).setScale(2, BigDecimal.ROUND_HALF_UP);
                    repaymentParentList.get(repaymentParentList.size() - 1).put("everyOverduePenalty", overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));


                }
            }

        } else {
            jsonObject.put("everyOverduePenalty", new BigDecimal(0.00));
        }
        //最终罚息
        jsonObject.put("sumyqmoney", overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));
        jsonObject.put("overduePenalty", overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));
        jsonObject.put("overduePenaltyTotal", overduePenalty.setScale(2, BigDecimal.ROUND_HALF_UP));
    }

    //计算剩余欠款逾期罚息 实体 销售合同
    public void calRemainingArrears(RepaymentEntity jsonObject, List<RepaymentEntity> repaymentParentList, String type) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        BigDecimal sumqkmoney = new BigDecimal(0.00);
        BigDecimal sumyqmoney = new BigDecimal(0.00);
        BigDecimal autalRepay = jsonObject.getRepaymentAmount();
        if (repaymentParentList.size() > 0) {
            for (int j = 0; j < repaymentParentList.size(); j++) {
                repaymentParentList.get(j).setRemainingArrears(new BigDecimal(0));
                repaymentParentList.get(j).setOverduePenalty(new BigDecimal(0));
                if (repaymentParentList.get(j).getHkType() != 2 && repaymentParentList.get(j).getHkType() != 3) {
                    autalRepay = repaymentParentList.get(j).getRepaymentAmount().add(autalRepay);
                }
            }
            if (between_days(jsonObject.getRepaymentDate(), sdf.format(new Date())) >= 0) {
                if (type.equals("0")) {
                    sumqkmoney = sumqkmoney.add(jsonObject.getContractRepaymentAmount().subtract(autalRepay).compareTo(new BigDecimal(0.00)) > 0 ? jsonObject.getContractRepaymentAmount().subtract(autalRepay) : new BigDecimal(0));
                } else {
                    sumqkmoney = sumqkmoney.add(jsonObject.getTotal().subtract(autalRepay).compareTo(new BigDecimal(0.00)) > 0 ? jsonObject.getTotal().subtract(autalRepay) : new BigDecimal(0));
                }
            }
        } else {
            if (between_days(jsonObject.getRepaymentDate(), sdf.format(new Date())) >= 0) {
                if (type.equals("0")) {
                    sumqkmoney = sumqkmoney.add(jsonObject.getContractRepaymentAmount().subtract(autalRepay).compareTo(new BigDecimal(0.00)) > 0 ? jsonObject.getContractRepaymentAmount().subtract(autalRepay) : new BigDecimal(0));

                } else {
                    sumqkmoney = sumqkmoney.add(jsonObject.getTotal().subtract(autalRepay).compareTo(new BigDecimal(0.00)) > 0 ? jsonObject.getTotal().subtract(autalRepay) : new BigDecimal(0));
                }
            }
        }
        //先算剩余欠款
        jsonObject.setRemainingArrears(sumqkmoney.setScale(2, BigDecimal.ROUND_HALF_UP));
        //根据剩余欠款算逾期罚息
        calOverduePenalty(jsonObject, repaymentParentList, type);

    }

    public void calOverduePenalty(RepaymentEntity jsonObject, List<RepaymentEntity> repaymentParentList, String type) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //约定还款日期
        String repaymentDate = jsonObject.getRepaymentDate();
        //约定还款金额
        BigDecimal repayMentMoney = null;
        //判断是否计算逾期
        Boolean yq = false;
        //获取冲抵罚息
        BigDecimal cdOverdue = jsonObject.getCdOverduePenalty();
        if (type.equals("0")) {
            repayMentMoney = jsonObject.getContractRepaymentAmount();
        } else {
            repayMentMoney = jsonObject.getTotal();
        }
        String nowDate = sdf.format(new Date());
        //剩余总欠款
        BigDecimal remainingArrears = jsonObject.getRemainingArrears();
        //最后实际还款日期
        String lastActualRepaymentDate = nowDate;
        BigDecimal overduePenalty = new BigDecimal(0.00);

        BigDecimal everyRemainingArrear = new BigDecimal(0.00);

        //判断剩余欠款的实际还款有几条
        int sumRepay = 0;
        BigDecimal yhOver = new BigDecimal(0.00);
        ;
        //判断主的是逾期罚息还是剩余欠款
        if (jsonObject.getHkType() != 2 && jsonObject.getHkType() != 3) {
            sumRepay = sumRepay + 1;
            everyRemainingArrear = everyRemainingArrear.add(jsonObject.getRepaymentAmount());
            if (StringUtils.isNotEmpty(jsonObject.getActualRepaymentDate())) {
                lastActualRepaymentDate = jsonObject.getActualRepaymentDate();

            }
            if (between_days(repaymentDate, lastActualRepaymentDate) > 7) {
                yq = true;
            }
        } else {
            yhOver = yhOver.add(jsonObject.getRepaymentAmount());
        }
        //主的剩余欠款
        jsonObject.setEveryRemainingArrear(repayMentMoney.subtract(everyRemainingArrear));
        jsonObject.setEveryOverduePenalty(new BigDecimal(0.00));
        int jsOverdue = 0;

        if (between_days(repaymentDate, nowDate) > 0) {
            //判断最后一条的日期与约定还款日期的大小{当前日期-约定日期)*0.0007*总剩余欠款
            if (null != repaymentParentList && repaymentParentList.size() > 0) {

                int sumQkHk = 0;
                for (int i = 0; i < repaymentParentList.size(); i++) {
                    if (repaymentParentList.get(i).getHkType() != 2 && repaymentParentList.get(i).getHkType() != 3) {
                        sumRepay = sumRepay + 1;
                        sumQkHk = i;
                        //计算每期剩余欠款,便于计算每期的逾期罚息
                        everyRemainingArrear = everyRemainingArrear.add(repaymentParentList.get(i).getRepaymentAmount());
                        if (between_days(repaymentDate, repaymentParentList.get(i).getActualRepaymentDate()) > 7) {
                            yq = true;
                        }
                    }
                    repaymentParentList.get(i).setEveryOverduePenalty(new BigDecimal(0.00));
                    repaymentParentList.get(i).setEveryRemainingArrear(repayMentMoney.subtract(everyRemainingArrear));
                }
                //实际还款为欠款还款的最后一条的日期
                lastActualRepaymentDate = repaymentParentList.get(sumQkHk).getActualRepaymentDate();
            }
        }
        //判断是否计算逾期
        if ((between_days(repaymentDate, nowDate) > 0 && yq)
                || (remainingArrears.compareTo(new BigDecimal(0.00)) > 0 && between_days(repaymentDate, nowDate) > 7)
        ) {

            //判断最后一条的日期与约定还款日期的大小{当前日期-约定日期)*0.0007*总剩余欠款
            if (between_days(lastActualRepaymentDate, repaymentDate) >= 0 || StringUtils.isBlank(jsonObject.getActualRepaymentDate())) {
                //（当前日期-约定日期）*总剩余欠款*0.0007
                overduePenalty = overduePenalty.add(remainingArrears.multiply(new BigDecimal(between_days(repaymentDate, nowDate) * 0.0007))).setScale(2, BigDecimal.ROUND_HALF_UP);
                //其他为0，最后一条为逾期罚息
                if (null != repaymentParentList && repaymentParentList.size() > 0) {
                    for (int i = 0; i < repaymentParentList.size(); i++) {
                        repaymentParentList.get(i).setEveryOverduePenalty(new BigDecimal(0.00));
                    }
                } else {
                    jsonObject.setEveryOverduePenalty(overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));
                }
            } else {
                //判断计算罚息的期数是否包含主的，如果包含，主的为（本期-约定）*上期欠款*0.0007，其他期数为（本期-上期）
                if (between_days(repaymentDate, jsonObject.getActualRepaymentDate()) > 0) {
                    jsOverdue = jsOverdue + 1;
                    overduePenalty = overduePenalty.add(repayMentMoney.multiply(
                            new BigDecimal(between_days(repaymentDate, jsonObject.getActualRepaymentDate()) * 0.0007))).setScale(2, BigDecimal.ROUND_HALF_UP);
                    //如果还款只有一条并且是主的，那么就加上最后的那个计算
                    if (sumRepay == 1) {
                        //最后加上（当前日期-最后一天日期）*所有欠款*0.0007
                        overduePenalty = overduePenalty.add(remainingArrears.multiply(new BigDecimal(between_days(lastActualRepaymentDate, nowDate) * 0.0007))).setScale(2, BigDecimal.ROUND_HALF_UP);
                    }
                    //主的的罚息

                    jsonObject.setEveryOverduePenalty(overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));

                }
                if (null != repaymentParentList && repaymentParentList.size() > 0) {
                    if (jsOverdue == 1) {
                        //主的计算
                        for (int i = 0; i < repaymentParentList.size(); i++) {
                            repaymentParentList.get(i).setEveryOverduePenalty(new BigDecimal(0.00));
                            if (repaymentParentList.get(i).getHkType() == 2 || repaymentParentList.get(i).getHkType() == 3) {
                                yhOver = yhOver.add(repaymentParentList.get(i).getRepaymentAmount());
                            }
                            if (between_days(repaymentDate, repaymentParentList.get(i).getActualRepaymentDate()) > 0) {
                                //判断是否是多期,其他期数为（本期-上期）*上期欠款*0.0007

                                if (i == 0) {
                                    //i==0;本期-主的
                                    overduePenalty = overduePenalty.add(jsonObject.getEveryRemainingArrear().multiply(
                                            new BigDecimal(between_days(jsonObject.getActualRepaymentDate(), repaymentParentList.get(i).getActualRepaymentDate()) * 0.0007))).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    repaymentParentList.get(i).setEveryOverduePenalty(overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));


                                } else {
                                    //获取上一期不是逾期罚息的那一期
                                    int qkDate = 0;
                                    for (int j = i - 1; j >= 0; j--) {
                                        if (repaymentParentList.get(j).getHkType() != 2 && repaymentParentList.get(j).getHkType() != 3) {
                                            qkDate = j;
                                            break;
                                        }
                                    }
                                    overduePenalty = overduePenalty.add(repaymentParentList.get(qkDate).getEveryRemainingArrear().multiply(
                                            new BigDecimal(between_days(repaymentParentList.get(qkDate).getActualRepaymentDate(), repaymentParentList.get(i).getActualRepaymentDate()) * 0.0007))).setScale(2, BigDecimal.ROUND_HALF_UP);
                                    repaymentParentList.get(i).setEveryOverduePenalty(overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));


                                }
                            }
                        }
                    } else {
                        //主的不进行计算逾期
                        for (int i = 0; i < repaymentParentList.size(); i++) {
                            repaymentParentList.get(i).setEveryOverduePenalty(new BigDecimal(0.00));
                            if (repaymentParentList.get(i).getHkType() == 2 || repaymentParentList.get(i).getHkType() == 3) {
                                yhOver = yhOver.add(repaymentParentList.get(i).getRepaymentAmount());
                            }
                            if (between_days(repaymentDate, repaymentParentList.get(i).getActualRepaymentDate()) > 0) {
                                //计算的第一期为（本期-约定）*本期欠款*0.0007，其他期数为（本期-上期）
                                jsOverdue = jsOverdue + 1;
                                if (jsOverdue == 1) {
                                    if (i == 0) {
                                        //上期欠款为主的
                                        overduePenalty = overduePenalty.add(jsonObject.getEveryRemainingArrear().multiply(
                                                new BigDecimal(between_days(repaymentDate, repaymentParentList.get(i).getActualRepaymentDate()) * 0.0007))).setScale(2, BigDecimal.ROUND_HALF_UP);

                                        repaymentParentList.get(i).setEveryOverduePenalty(overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));


                                    } else {
                                        int qkDate = 0;
                                        for (int j = i - 1; j >= 0; j--) {
                                            if (repaymentParentList.get(j).getHkType() != 2 && repaymentParentList.get(j).getHkType() != 3) {
                                                qkDate = j;
                                                break;
                                            }
                                        }
                                        overduePenalty = overduePenalty.add(repaymentParentList.get(qkDate).getEveryRemainingArrear().multiply(
                                                new BigDecimal(between_days(repaymentDate, repaymentParentList.get(i).getActualRepaymentDate()) * 0.0007))).setScale(2, BigDecimal.ROUND_HALF_UP);
                                        repaymentParentList.get(i).setEveryOverduePenalty(overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));

                                    }
                                } else {
                                    int qkDate = 0;
                                    for (int j = i - 1; j >= 0; j--) {
                                        if (repaymentParentList.get(j).getHkType() != 2 && repaymentParentList.get(j).getHkType() != 3) {
                                            qkDate = j;
                                            break;
                                        }
                                    }
                                    overduePenalty = overduePenalty.add(repaymentParentList.get(qkDate).getEveryRemainingArrear().multiply(
                                            new BigDecimal(between_days(repaymentParentList.get(qkDate).getActualRepaymentDate(), repaymentParentList.get(i).getActualRepaymentDate()) * 0.0007)));
                                    repaymentParentList.get(i).setEveryOverduePenalty(overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));

                                }
                            }
                        }
                    }
                    //最后加上（当前日期-最后一天日期）*所有欠款*0.0007
                    overduePenalty = overduePenalty.add(remainingArrears.multiply(new BigDecimal(between_days(lastActualRepaymentDate, nowDate) * 0.0007))).setScale(2, BigDecimal.ROUND_HALF_UP);
                    repaymentParentList.get(repaymentParentList.size() - 1).setEveryOverduePenalty(overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));


                }
            }

        }
        //最终罚息
        jsonObject.setOverduePenalty(overduePenalty.subtract(yhOver).setScale(2, BigDecimal.ROUND_HALF_UP));
        jsonObject.setOverduePenaltyTotal(overduePenalty.setScale(2, BigDecimal.ROUND_HALF_UP));
    }

    //计算剩余欠款逾期罚息 JSON 融资合同
    public void calRemainingArrears(JSONObject jsonObject, List<JSONObject> repaymentParentList) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        BigDecimal autalRepay = jsonObject.getBigDecimal("advancesMoney");
        BigDecimal sumqkmoney = new BigDecimal(0.00);
        BigDecimal sumyqmoney = new BigDecimal(0.00);
        jsonObject.put("remainingArrears", new BigDecimal(0.00));
        if (repaymentParentList.size() > 0) {
            for (int j = 0; j < repaymentParentList.size(); j++) {
                repaymentParentList.get(j).put("remainingArrears", new BigDecimal(0));
                autalRepay = repaymentParentList.get(j).getBigDecimal("advancesMoney").add(autalRepay);
            }
            if (between_days(jsonObject.getString("financingDate"), sdf.format(new Date())) >= 0) {
                sumqkmoney = sumqkmoney.add(jsonObject.getBigDecimal("financingMoney")
                        .subtract(autalRepay).compareTo(new BigDecimal(0.00)) > 0 ?
                        jsonObject.getBigDecimal("financingMoney").subtract(autalRepay)
                        : new BigDecimal(0));
            }
        } else {
            if (between_days(jsonObject.getString("financingDate"), sdf.format(new Date())) >= 0) {
                sumqkmoney = sumqkmoney.add(jsonObject.getBigDecimal("financingMoney")
                        .subtract(autalRepay).compareTo(new BigDecimal(0.00)) > 0 ?
                        jsonObject.getBigDecimal("financingMoney").subtract(autalRepay) : new BigDecimal(0));
            }
        }

        //先算剩余欠款
        jsonObject.put("remainingArrears", sumqkmoney.setScale(2, BigDecimal.ROUND_HALF_UP));
        jsonObject.put("sumqkmoney", sumqkmoney.setScale(2, BigDecimal.ROUND_HALF_UP));
        //根据剩余欠款算逾期罚息
        calOverduePenalty(jsonObject, repaymentParentList);


    }

    public void calOverduePenalty(JSONObject jsonObject, List<JSONObject> repaymentParentList) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //约定还款日期
        String repaymentDate = jsonObject.getString("financingDate");
        BigDecimal sumyqmoney = new BigDecimal(0.00);
        //约定还款金额
        BigDecimal repayMentMoney = jsonObject.getBigDecimal("financingMoney");
        //获取冲抵罚息
        BigDecimal cdOverdue = jsonObject.getBigDecimal("cdOverduePenalty");
        String nowDate = sdf.format(new Date());
        //剩余总欠款
        BigDecimal remainingArrears = jsonObject.getBigDecimal("remainingArrears");
        //最后实际还款日期
        String lastActualRepaymentDate = repaymentDate;
        //逾期罚息
        BigDecimal overduePenalty = new BigDecimal(0.00);
        BigDecimal everyRemainingArrear = new BigDecimal(0.00);
        //判断剩余欠款的实际还款有几条
        int sumRepay = 0;
        //判断主的是逾期罚息还是剩余欠款
        if (null != jsonObject && jsonObject.getInteger("hkType") != 2 && jsonObject.getInteger("hkType") != 3) {
            sumRepay = sumRepay + 1;
            everyRemainingArrear = everyRemainingArrear.add(jsonObject.getBigDecimal("advancesMoney"));
            if (StringUtils.isNotEmpty(jsonObject.getString("advancesDate"))) {
                lastActualRepaymentDate = jsonObject.getString("advancesDate");
            }
        }
        //主的剩余欠款
        jsonObject.put("everyRemainingArrear", repayMentMoney.subtract(everyRemainingArrear));
        int jsOverdue = 0;
        overDueDetailDao.removeByCondition(" and MAIN_ID=?", new String[]{jsonObject.getString("id")});
        //判断是否计算逾期
        if (between_days(repaymentDate, nowDate) > 0) {
            //判断实际还款有几条
            if (null != repaymentParentList && repaymentParentList.size() > 0) {
                int sumQkHk = 0;
                for (int i = 0; i < repaymentParentList.size(); i++) {
                    if (repaymentParentList.get(i).getInteger("hkType") != 2 && repaymentParentList.get(i).getInteger("hkType") != 3) {
                        sumRepay = sumRepay + 1;
                        sumQkHk = i;
                        //计算每期剩余欠款,便于计算每期的逾期罚息
                        everyRemainingArrear = everyRemainingArrear.add(repaymentParentList.get(i).getBigDecimal("advancesMoney"));
                    }
                    repaymentParentList.get(i).put("everyRemainingArrear", repayMentMoney.subtract(everyRemainingArrear));
                }
                //实际还款为欠款还款的最后一条的日期
                lastActualRepaymentDate = repaymentParentList.get(sumQkHk).getString("advancesDate");
            }
        }
        jsonObject.put("sumyqmoney", jsonObject.getBigDecimal("jroverduePenalty").setScale(2, BigDecimal.ROUND_HALF_UP));
        jsonObject.put("jroverduePenalty", jsonObject.getBigDecimal("jroverduePenalty").setScale(2, BigDecimal.ROUND_HALF_UP));
    }

    //计算剩余欠款逾期罚息 实体  融资合同
    public void calRemainingArrears(FinancingEntity jsonObject, List<FinancingEntity> repaymentParentList) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        BigDecimal sumqkmoney = new BigDecimal(0.00);
        BigDecimal sumyqmoney = new BigDecimal(0.00);
        BigDecimal autalRepay = jsonObject.getAdvancesMoney();

        if (repaymentParentList.size() > 0) {
            for (int j = 0; j < repaymentParentList.size(); j++) {
                repaymentParentList.get(j).setRemainingArrears(new BigDecimal(0));
                autalRepay = repaymentParentList.get(j).getAdvancesMoney().add(autalRepay);
            }
            if (between_days(jsonObject.getFinancingDate(), sdf.format(new Date())) >= 0) {
                sumqkmoney = sumqkmoney.add(jsonObject.getFinancingMoney().subtract(autalRepay).compareTo(new BigDecimal(0.00)) > 0 ? jsonObject.getFinancingMoney().subtract(autalRepay) : new BigDecimal(0));
            }
        } else {
            if (between_days(jsonObject.getFinancingDate(), sdf.format(new Date())) >= 0) {
                sumqkmoney = sumqkmoney.add(jsonObject.getFinancingMoney().subtract(autalRepay).compareTo(new BigDecimal(0.00)) > 0 ? jsonObject.getFinancingMoney().subtract(autalRepay) : new BigDecimal(0));
            }
        }
        //先算剩余欠款
        jsonObject.setRemainingArrears(sumqkmoney.setScale(2, BigDecimal.ROUND_HALF_UP));
        //根据剩余欠款算逾期罚息
        calOverduePenalty(jsonObject, repaymentParentList);
    }

    public void calOverduePenalty(FinancingEntity jsonObject, List<FinancingEntity> repaymentParentList) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //约定还款日期
        String repaymentDate = jsonObject.getFinancingDate();
        //约定还款金额
        BigDecimal repayMentMoney = jsonObject.getFinancingMoney();
        String nowDate = sdf.format(new Date());
        //剩余总欠款
        BigDecimal remainingArrears = jsonObject.getRemainingArrears();
        //最后实际还款日期
        String lastActualRepaymentDate = repaymentDate;
        BigDecimal overduePenalty = new BigDecimal(0.00);

        BigDecimal everyRemainingArrear = new BigDecimal(0.00);
        //判断剩余欠款的实际还款有几条
        int sumRepay = 0;
        //判断主的是逾期罚息还是剩余欠款
        if (jsonObject.getHkType() != 2 && jsonObject.getHkType() != 3) {
            sumRepay = sumRepay + 1;
            everyRemainingArrear = everyRemainingArrear.add(jsonObject.getAdvancesMoney());
            if (StringUtils.isNotEmpty(jsonObject.getAdvancesDate())) {
                lastActualRepaymentDate = jsonObject.getAdvancesDate();

            }
        }
        //主的剩余欠款
        jsonObject.setEveryRemainingArrear(repayMentMoney.subtract(everyRemainingArrear));
        int jsOverdue = 0;
        //判断是否计算逾期
        if (between_days(repaymentDate, nowDate) > 0) {
            //判断实际还款有几条
            if (null != repaymentParentList && repaymentParentList.size() > 0) {

                int sumQkHk = 0;
                for (int i = 0; i < repaymentParentList.size(); i++) {
                    if (repaymentParentList.get(i).getHkType() != 2 && repaymentParentList.get(i).getHkType() != 3) {
                        sumRepay = sumRepay + 1;
                        sumQkHk = i;
                        //计算每期剩余欠款,便于计算每期的逾期罚息
                        everyRemainingArrear = everyRemainingArrear.add(repaymentParentList.get(i).getAdvancesMoney());
                    }
                    repaymentParentList.get(i).setEveryRemainingArrear(repayMentMoney.subtract(everyRemainingArrear));
                }
                //实际还款为欠款还款的最后一条的日期
                lastActualRepaymentDate = repaymentParentList.get(sumQkHk).getAdvancesDate();
            }
            //判断最后一条的日期与约定还款日期的大小{当前日期-约定日期)*0.0007*总剩余欠款
            if (between_days(lastActualRepaymentDate, repaymentDate) > 0) {
                //（当前日期-约定日期）*总剩余欠款*0.0007
                overduePenalty = overduePenalty.add(remainingArrears.multiply(new BigDecimal(between_days(repaymentDate, nowDate) * 0.0007)));
            } else {
                //判断计算罚息的有几期
                //判断计算罚息的期数是否包含主的，如果包含，主的为（本期-约定）*上期欠款*0.0007，其他期数为（本期-上期）
                if (between_days(repaymentDate, jsonObject.getAdvancesDate()) > 0) {
                    jsOverdue = jsOverdue + 1;
                    overduePenalty = overduePenalty.add(repayMentMoney.multiply(
                            new BigDecimal(between_days(repaymentDate, jsonObject.getAdvancesDate()) * 0.0007)));
                }
                if (null != repaymentParentList && repaymentParentList.size() > 0) {
                    if (jsOverdue == 1) {
                        //主的计算
                        for (int i = 0; i < repaymentParentList.size(); i++) {
                            if (between_days(repaymentDate, repaymentParentList.get(i).getAdvancesDate()) > 0) {
                                //判断是否是多期,其他期数为（本期-上期）*上期欠款*0.0007
                                if (i == 0) {
                                    //i==0;本期-主的
                                    overduePenalty = overduePenalty.add(jsonObject.getEveryRemainingArrear().multiply(
                                            new BigDecimal(between_days(jsonObject.getAdvancesDate(), repaymentParentList.get(i).getAdvancesDate()) * 0.0007)));
                                } else {
                                    //获取上一期不是逾期罚息的那一期
                                    int qkDate = 0;
                                    for (int j = i - 1; j >= 0; j--) {
                                        if (repaymentParentList.get(j).getHkType() != 2 && repaymentParentList.get(j).getHkType() != 3) {
                                            qkDate = j;
                                            break;
                                        }
                                    }
                                    overduePenalty = overduePenalty.add(repaymentParentList.get(qkDate).getEveryRemainingArrear().multiply(
                                            new BigDecimal(between_days(repaymentParentList.get(qkDate).getAdvancesDate(), repaymentParentList.get(i).getAdvancesDate()) * 0.0007)));
                                }
                            }
                        }
                    } else {
                        //主的不进行计算逾期
                        for (int i = 0; i < repaymentParentList.size(); i++) {
                            if (between_days(repaymentDate, repaymentParentList.get(i).getAdvancesDate()) > 0) {
                                //计算的第一期为（本期-约定）*本期欠款*0.0007，其他期数为（本期-上期）
                                jsOverdue = jsOverdue + 1;
                                if (jsOverdue == 1) {
                                    if (i == 0) {
                                        //上期欠款为主的
                                        overduePenalty = overduePenalty.add(jsonObject.getEveryRemainingArrear().multiply(
                                                new BigDecimal(between_days(repaymentDate, repaymentParentList.get(i).getAdvancesDate()) * 0.0007)));
                                    } else {
                                        int qkDate = 0;
                                        for (int j = i - 1; j >= 0; j--) {
                                            if (repaymentParentList.get(j).getHkType() != 2 && repaymentParentList.get(j).getHkType() != 3) {
                                                qkDate = j;
                                                break;
                                            }
                                        }
                                        overduePenalty = overduePenalty.add(repaymentParentList.get(qkDate).getEveryRemainingArrear().multiply(
                                                new BigDecimal(between_days(repaymentDate, repaymentParentList.get(i).getAdvancesDate()) * 0.0007)));
                                    }
                                } else {
                                    int qkDate = 0;
                                    for (int j = i - 1; j >= 0; j--) {
                                        if (repaymentParentList.get(j).getHkType() != 2 && repaymentParentList.get(j).getHkType() != 3) {
                                            qkDate = j;
                                            break;
                                        }
                                    }
                                    overduePenalty = overduePenalty.add(repaymentParentList.get(qkDate).getEveryRemainingArrear().multiply(
                                            new BigDecimal(between_days(repaymentParentList.get(qkDate).getAdvancesDate(), repaymentParentList.get(i).getAdvancesDate()) * 0.0007)));
                                }
                            }
                        }
                    }

                }
                //最后加上（当前日期-最后一天日期）*所有欠款*0.0007
                overduePenalty = overduePenalty.add(remainingArrears.multiply(new BigDecimal(between_days(lastActualRepaymentDate, nowDate) * 0.0007)));
            }
        }
    }


    //保存逾期罚款明细
    public void saveOverDueDetail(String mainId, String startTime, String endTime, BigDecimal overduePenaltyAmount) {

        OverDueDetail overDueDetail = new OverDueDetail();
        overDueDetail.setMainId(mainId);
        overDueDetail.setOverduePenaltyAmount(overduePenaltyAmount);
        overDueDetail.setStartTime(startTime);
        overDueDetail.setEndTime(endTime);
        overDueDetailDao.add(overDueDetail);

    }

    //身份证验证
    private String matchesOdd(String matchesCard) {
        if (StringUtils.isBlank(matchesCard)) {
            return "";
        }
        String pattern = "^(\\d{6})(\\d{4})(\\d{2})(\\d{2})(\\d{3})([0-9]|X)$";
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(matchesCard);
        if (m.matches()) {
            return execute(matchesCard);
        }
        return "";
    }

    public String execute(String value) {
        value = value.trim();
        if (value == null || (value.length() != 15 && value.length() != 18)) {
            return "";
        }
        if (value.length() == 15 || value.length() == 18) {
            String lastValue = value.substring(value.length() - 1, value.length());
            String lastValues = value.substring(value.length() - 2, value.length() - 1);
            int sex;
            if (lastValue.trim().toLowerCase().equals("x") || lastValue.trim().toLowerCase().equals("e")) {
                return "先生";
            } else {
                sex = Integer.parseInt(lastValues) % 2;
                return sex == 0 ? "女士" : "先生";
            }
        } else {
            return "";
        }
    }

}
